Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to list while loading from json

Tags:

python

json

Json is below. I need to convert to list after loading from the json. I am getting as str

{
  "1": {
    "Data (L)": "[  { \"S\" : \"168\" }]"
  },
  "2": {
    "Data (L)": "[  { \"S\" : \"169\" }]"
  }
}

Code

with open('a.json') as f:
    a = json.loads(f.read())
print (a)
data1 = []
for i,j in a.items():
    data = {}
    data['id'] = i
    data1.append(data)
    for k,l in j.items():
        data[k] = l
        print (type(l))
        print (l)

My type pf l is <class 'str'> where output of l is [ { "S" : "168" }]

Expected out

print type(l) has to be list not str

like image 809
aysh Avatar asked Jan 26 '26 00:01

aysh


1 Answers

I'm assuming, you have double-encoded json. Just call another json.loads() on values of second dictionaries:

import json

json_text = r'''{
  "1": {
    "Data (L)": "[  { \"S\" : \"168\" }]"
  },
  "2": {
    "Data (L)": "[  { \"S\" : \"169\" }]"
  }
}'''

data = json.loads(json_text)

for k, v in data.items():
    for kk, vv in v.items():
        vv = json.loads(vv)
        print(type(vv))
        print(vv)

Prints:

<class 'list'>
[{'S': '168'}]
<class 'list'>
[{'S': '169'}]
like image 100
Andrej Kesely Avatar answered Jan 28 '26 15:01

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!