簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM