首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python字典创建的嵌套json

使用python字典创建的嵌套json
EN

Stack Overflow用户
提问于 2016-06-16 20:52:14
回答 1查看 86关注 0票数 1

我有在多个层次上运行的for循环。循环的每一层都会返回一个需要放入层次结构中的json。

代码语言:javascript
复制
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

错误如下

代码语言:javascript
复制
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。就像这样

代码语言:javascript
复制
aid:ajson 
  |
  ---bid:bjson
      |
       --- cid:cjson
             |
             etc. 
EN

回答 1

Stack Overflow用户

发布于 2016-06-16 20:59:17

看起来ajson是一个字符串。您可能想要解析这个。您可以使用python标准库json并调用json.loads(ajson)

示例:

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37859823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档