我有如下所示的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获得所需的输出吗?
发布于 2018-10-17 00:35:37
这里是一个起点,为给出的例子工作。可能需要根据其他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希望这能有所帮助。如果这不是你想要的,请留下评论,并努力改进。
https://stackoverflow.com/questions/52827992
复制相似问题