3

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

aysh
  • 493
  • 1
  • 11
  • 23

2 Answers2

4

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'}]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
-1

It is not a recommend method!

It is not secure to use eval() function this way. See Eval really is dangerous. (Thanks to @KarlKnechtel for the comment!)

Instead ast.literal_eval() can be used. See Using python's eval() vs. ast.literal_eval()?. (Thanks to @Sushanth for the comment!)


Initial answer below

You can use the built-in eval() function like the following:

s = "[  { \"S\" : \"168\" }]"
t = eval(s)

print(t)
print(type(t))
print(t[0])
print(type(t[0]))

which prints

[{'S': '168'}]
<class 'list'>
{'S': '168'}
<class 'dict'>
Gorisanson
  • 2,202
  • 1
  • 9
  • 25