anu010291
anu010291

Reputation: 85

Group JSON object using key in python

I have have JSON data as given below,

{
  "BLE:ble_type1": "xx",
  "BLE:ble_mac1": "yy",
  "BLE:ble_type2": "aa",
  "BLE:ble_mac2": "bb"
}

and the expected output is,

"BLE":[  
        {  
          "ble_type1":"xx",
          "ble_mac1":"yy"
        },
        {  
          "ble_type2":"aa",
          "ble_mac2":"bb"
        }
      ]

Can someone help me out in getting the required output using python?

Upvotes: 1

Views: 1810

Answers (1)

Here's a starting point, works for the example given. Likely will need to adjust for other JSON input data:

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}    


Now you have a new dict that contains the desired output:

>>> print(new_d)

{'BLE': [{'ble_type1': 'xx', 'ble_mac1': 'yy'}, {'ble_type2': 'aa', 'ble_mac2': 'bb'}]}

We can verify this matches the desired output:

>>> desired = [  
        {  
          "ble_type1":"xx",
          "ble_mac1":"yy"
        },
        {  
          "ble_type2":"aa",
          "ble_mac2":"bb"
        }
      ]

>>> print(new_d['BLE'] == desired)
True

Hope this helps. If it is not as you wanted, please leave a comment and will try to improve.

Upvotes: 1

Related Questions