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

2
  • Can you please edit your question and put there expected output? Commented Aug 2, 2020 at 6:30
  • Okay, but why does your json contain these weird strings, instead of the structured data that you want? Commented Aug 2, 2020 at 6:45

2 Answers 2

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'}]
Sign up to request clarification or add additional context in comments.

Comments

-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'>

3 Comments

Please do not ever recommend eval for this purpose. It is not secure.
@KarlKnechtel Thanks for your comment! I'm not proud to say it, but I didn't know that.
Instead better choice would be ast.literal_eval

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.