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

问题描述 投票:0回答:1

我在文件中有以下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 - 但只是一遍又一遍地返回第一个字典中的值:(

python json python-3.x
1个回答
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'列表中的第一项(字典)。

© www.soinside.com 2019 - 2024. All rights reserved.