1

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?

4
  • There is no such function that works like you are expecting. You need to split this json and make as you want it by using for loop. Commented Oct 16, 2018 at 4:43
  • Thanks.yes i am able to achieve this, "BLE":[ { "type1":"reference", "mac1":"aa:dd:dd:dd:dd" "type2":"environment", "mac2":"12:dd:ss:aa:ss" } ] Commented Oct 16, 2018 at 5:10
  • how are you reading the JSON data, from file or string? is it already stored in a variable, if so is its datatype dict? Commented Oct 16, 2018 at 5:40
  • @davedwards the data is stored in a variable and yes the datatype is dict Commented Oct 16, 2018 at 6:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much ..will check the code and get back to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.