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

2024-09-27 21:24:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有for循环在多个层次上运行。每一级循环都返回一个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. 

Tags: inapijsonforoutput层次结构hitbid
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:52

似乎ajson是一个字符串。你可能想分析一下。您可以使用python标准库^{}并调用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)

相关问题 更多 >

    热门问题