使用 python 中的键对 JSON 对象进行分组
Group JSON object using key in python
我有 JSON 数据如下,
{
"BLE:ble_type1": "xx",
"BLE:ble_mac1": "yy",
"BLE:ble_type2": "aa",
"BLE:ble_mac2": "bb"
}
预期的输出是,
"BLE":[
{
"ble_type1":"xx",
"ble_mac1":"yy"
},
{
"ble_type2":"aa",
"ble_mac2":"bb"
}
]
有人可以帮助我使用 python 获得所需的输出吗?
这是一个起点,适用于给定的示例。可能需要针对其他 JSON 输入数据进行调整:
from collections import OrderedDict
d = {
"BLE:ble_type1": "xx",
"BLE:ble_mac1": "yy",
"BLE:ble_type2": "aa",
"BLE:ble_mac2": "bb"
}
od = OrderedDict(d.items())
mainkey = set([k.split(':')[0] for k in list(d.keys())]).pop()
keys = [k.split(':')[1] for k in od.keys()]
values = list(od.values())
print(keys)
data = []
count = int(keys[0][-1])
d = {}
for k, v in zip(keys, values):
n = int(k[-1])
if n == count:
d[k] = v
else:
d = {}
count += 1
if n == count:
d[k] = v
if d not in data:
data.append(d)
new_d = {mainkey: data}
现在您有一个包含所需输出的新 dict
:
>>> print(new_d)
{'BLE': [{'ble_type1': 'xx', 'ble_mac1': 'yy'}, {'ble_type2': 'aa', 'ble_mac2': 'bb'}]}
我们可以验证这与所需的输出相匹配:
>>> desired = [
{
"ble_type1":"xx",
"ble_mac1":"yy"
},
{
"ble_type2":"aa",
"ble_mac2":"bb"
}
]
>>> print(new_d['BLE'] == desired)
True
希望这对您有所帮助。如果不是你想要的,请留言,我们会努力改进。
我有 JSON 数据如下,
{
"BLE:ble_type1": "xx",
"BLE:ble_mac1": "yy",
"BLE:ble_type2": "aa",
"BLE:ble_mac2": "bb"
}
预期的输出是,
"BLE":[
{
"ble_type1":"xx",
"ble_mac1":"yy"
},
{
"ble_type2":"aa",
"ble_mac2":"bb"
}
]
有人可以帮助我使用 python 获得所需的输出吗?
这是一个起点,适用于给定的示例。可能需要针对其他 JSON 输入数据进行调整:
from collections import OrderedDict
d = {
"BLE:ble_type1": "xx",
"BLE:ble_mac1": "yy",
"BLE:ble_type2": "aa",
"BLE:ble_mac2": "bb"
}
od = OrderedDict(d.items())
mainkey = set([k.split(':')[0] for k in list(d.keys())]).pop()
keys = [k.split(':')[1] for k in od.keys()]
values = list(od.values())
print(keys)
data = []
count = int(keys[0][-1])
d = {}
for k, v in zip(keys, values):
n = int(k[-1])
if n == count:
d[k] = v
else:
d = {}
count += 1
if n == count:
d[k] = v
if d not in data:
data.append(d)
new_d = {mainkey: data}
现在您有一个包含所需输出的新
dict
:
>>> print(new_d)
{'BLE': [{'ble_type1': 'xx', 'ble_mac1': 'yy'}, {'ble_type2': 'aa', 'ble_mac2': 'bb'}]}
我们可以验证这与所需的输出相匹配:
>>> desired = [
{
"ble_type1":"xx",
"ble_mac1":"yy"
},
{
"ble_type2":"aa",
"ble_mac2":"bb"
}
]
>>> print(new_d['BLE'] == desired)
True
希望这对您有所帮助。如果不是你想要的,请留言,我们会努力改进。