python - 在 Python 中从 json 创建新数组
问题描述
如果您有来自 url 的多级嵌套 json:
import json
import urllib.request
data = urllib.request.urlopen("https://url").read()
output = json.loads(data)
for each in output['toplevel']:
Key = each['Key']
Value = each['Value']
string = {Key:Value}
print(dict(new_context = string))
这个回报:
{'new_context': {'the_Key1': 'the_Value1'}}
{'new_context': {'the_Key2': 'the_Value2'}}
{'new_context': {'the_Key3': 'the_Value3'}}
我想要的是:
{'new_context': {'the_Key1': 'the_Value1', 'the_Key2': 'the_Value2', 'the_Key3': 'the_Value3'}}
解决方案
干得好 :
import json
import urllib.request
data = urllib.request.urlopen("https://url").read()
output = json.loads(data)
result = {"new_context": {}}
for each in output['toplevel']:
result["new_context"][each['Key']] = each['Value']
print(result)