skip to Main Content

I have a json object that looks something like this

[{'"p"': '{"n":"s","i":"1"}'},.....]

Just imagine multiple objects like this. I want to iterate through this and access n and i keys like a normal json but unfortunately, i am not able to figure it out.

I tried this –

for i in a:
    for j in i:
        j.replace("'"," ")
        for k,v in j:
            print(k,v)

But getting this

ValueError: not enough values to unpack (expected 2, got 1)

Is there any way i can convert that weird json into normal json like below

[{"p": {"n":"s","i":"1"}},.....]

Any help will be appreciated, Thank you.

2

Answers


  1. It looks like the keys and value of your dictionaries are json strings. You could loop through and convert them:

    import json
    
    a =  [{'"p"': '{"n":"s","i":"1"}'}]
    
    converted = [{json.loads(k): json.loads(v) for k, v in d.items()} for d in a]
    # [{'p': {'n': 's', 'i': '1'}}]
    

    If it’s possible, it’s worth checking to see it you can get proper data to start with because this seems like the source of the data is a problem.

    Login or Signup to reply.
  2. You can map the keys and values to json.loads to convert JSON-formatted objects to Python ones:

    [dict(map(json.loads, i) for i in d.items()) for d in a]
    

    Demo: https://replit.com/@blhsing/FlawedUtilizedPcboard

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search