JSON - 如何迭代列表中的嵌套字典

时间:2018-03-02 15:25:20

标签: python json python-3.x

我在文件中有以下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'])

返回:

output

我的问题是如何迭代"rows"中的所有嵌套词典 - 在这种情况下有2个。你可以看到我对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']:识别"rows"的正确数量 - 无论是2还是5o - 但只是一遍又一遍地返回第一个字典中的值:(

1 个答案:

答案 0 :(得分:1)

循环遍历['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'列表中的第一项(字典)。

相关问题