我有在多个级别上运行的循环。每个级别的循环返回一个需要放在层次结构中的json。
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
错误如下
Traceback (most recent call last):
File "Test.py", line 80, in <module>
output[aid][bid] = bjson
TypeError: 'unicode' object does not support item assignment
我们需要基于for循环创建具有嵌套层次结构的最终json。
之类的东西aid:ajson
|
---bid:bjson
|
--- cid:cjson
|
etc.
答案 0 :(得分:1)
似乎ajson
是一个字符串。您可能想要解析它。您可以使用python标准库What is __main__.py?并调用json.loads(ajson)
示例:
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)