首页 > 解决方案 > 使用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 获得所需的输出吗?

标签: arraysjsonpython-3.xiterationkey-value

解决方案


这是一个起点,适用于给出的示例。可能需要针对其他 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

希望这可以帮助。如果不是您想要的,请发表评论,并会努力改进。


推荐阅读