1

i have for loops running on the multiple levels . Each level of loop returns a json which needs to be put in a hierarchy .

output = {}
for a in alist:
  aid, ajson = hit_api(url1)
  output[aid] = ajson
  for b in blist:
    bid, bjson = hit_api(url2)
    output[aid][bid] = bjson -- this is where we are getting error

The error is as below

Traceback (most recent call last):
  File "Test.py", line 80, in <module>
    output[aid][bid] = bjson 
TypeError: 'unicode' object does not support item assignment

We need to create a final json with nested hierarchy based on the for loop. something like

aid:ajson 
  |
  ---bid:bjson
      |
       --- cid:cjson
             |
             etc. 

1 Answer 1

1

It seems like ajson is a string. You might want to parse this. You can use python standard library json and call json.loads(ajson)

Example:

import json
output = {}
for a in alist:
  aid, ajson = hit_api(url1)
  output[aid] = json.loads(ajson)
  for b in blist:
    bid, bjson = hit_api(url2)
    output[aid][bid] = json.loads(bjson)
Sign up to request clarification or add additional context in comments.

3 Comments

yeah.. all jsons are string.. but i dont want jsons to be on same hierarchy.. i want , bjson to be nested under ajson .
But still i end up in error output[aid] = json.load(str(ajson)) File "/usr/lib/python2.7/json/__init__.py", line 286, in load return loads(fp.read(), AttributeError: 'str' object has no attribute 'read'
Sorry, it should be json.loads, not json.load. I have updated answer

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.