arrays - 使用python中的键对JSON对象进行分组
问题描述
我有如下给出的 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
希望这可以帮助。如果不是您想要的,请发表评论,并会努力改进。
推荐阅读
- react-native - 反应原生。滚动到 ScrollView 内的元素的最佳方式
- c# - Dynamics 365 Online - v9 更新后从外部批次更新机会时出错
- python - 无法弄清楚这段代码有什么问题[python 3x]
- sql-server - SQL:管理表中的更改日志
- python - Beautifullsoup:如何获取标签中的内容
?
- kubernetes - 如何使用 client-go 向 Kubernetes API 提交通用“runtime.Object”
- python - ImportError 但软件存在于 conda 列表中
- wordpress - 如何获取在 WordPress 菜单区域页面下添加的所有添加类别?
- docker - Site unreachable with Hadoop on Docker
- php - 使用随机 PHP 用子字符串动态替换子字符串