[英]JSON - How to iterate nested dictionaries in a list
我的文件中包含以下JSON数据:
{
"Generic": {
"main": [{
"one": "Main 1",
"two": "Main 2"
}],
"rows": [
{
"row1": "This is row 1-1",
"row2": "This is row 2-1",
"row3": "This is row 3-1"
},
{
"row1": "This is row 1-2",
"row2": "This is row 2-2",
"row3": "This is row 3-2"
}
]
}
}
我可以这样访问值:
import json
with open(r'C:\generic.json') as json_data:
json_data = json.load(json_data)
for x in sorted(json_data):
print (x)
print ('main:')
print (json_data[x]['main'][0]['one'])
print (json_data[x]['main'][0]['two'])
print ('rows:')
print (json_data[x]['rows'][0]['row1'])
print (json_data[x]['rows'][0]['row2'])
print (json_data[x]['rows'][0]['row3'])
print ('')
for y in json_data[x]:
print (json_data[x]['rows'][0]['row1'])
返回:
我的问题是如何迭代"rows"
所有嵌套字典-在这种情况下,有2个。您可以for y in json_data[x]:
看到for y in json_data[x]:
可悲尝试for y in json_data[x]:
注意:我在第一个循环中访问"rows"
数据以显示它是可访问的-但我需要弄清楚如何在第二个循环中访问这些行。
任何帮助将不胜感激 :)
编辑:
我与以下人员更接近-我非常接近,但不确定我缺少的那一块小东西:
for x in sorted(json_data):
print (x)
print ('main:')
print (json_data[x]['main'][0]['one'])
print (json_data[x]['main'][0]['two'])
print ('rows:')
print (json_data[x]['rows'][0]['row1'])
print (json_data[x]['rows'][0]['row2'])
print (json_data[x]['rows'][0]['row3'])
print ('')
for r in json_data[x]['rows']:
print (json_data[x]['rows'][0]['row1'])
print (json_data[x]['rows'][0]['row2'])
print (json_data[x]['rows'][0]['row3'])
for r in json_data[x]['rows']:
的for r in json_data[x]['rows']:
识别正确数目的"rows"
-2或5o-只是一遍又一遍地从第一个字典返回值:(
遍历['rows']
,您只需要使用r
变量。 用这个:
for r in json_data['Generic']['rows']:
print(r['row1'])
print(r['row2'])
print(r['row3'])
输出:
This is row 1-1
This is row 2-1
This is row 3-1
This is row 1-2
This is row 2-2
This is row 3-2
只得到第一个字典的原因是-您在循环内使用了json_data[x]['rows'][0]
。 [0]
将始终为您提供'rows'
列表中的第一项(词典)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.