Python list json conversion to list

Viewed 71

I have a list in the below format.

['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']

I need to remove the data column from above list / json and replace it with key value of the list.

I need to transform it to the below structure. Desired output:

[
    {
     "score":111,
     "id":"de80ca97"
    },
    {
     "score":222,
     "id":"8916a167"
    },
    {
     "score":333,
     "id":"12966e98"
    }
]

Any suggestions or ideas most welcome.

1 Answers

You can use a for loop or you can also use a list comprehension as follows:

>>> import json
>>> l = ['111: {"id":"de80ca97","data":"test"}', '222: {"id":"8916a167","data":"touch"}', '333: {"id":"12966e98","data":"tap"}']
>>> [{'score': int(e.split()[0][:-1]), 'id': json.loads(e.split()[1])['id']} for e in l]

If you prefer to use a for loop:

new_l = []
for e in l:
    key, json_str = e.split()
    new_l.append({'score': int(key[:-1]), 'id': json.loads(json_str)['id']})
Related