简体   繁体   中英

JSON - How to iterate nested dictionaries in a list

I have the following JSON data in a file:

{
    "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"
            }
        ]
    }
}

I can access the values like so:

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'])

This returns:

产量

My problem is how do I iterate all of the nested dictionaries in "rows" - in this case there are 2. You can see my sad attempt at for y in json_data[x]:

Note: I access the "rows" data in the the 1st loop to show that it is accessible - but I need to figure out how to access those rows in a 2nd loop.

Any help will be greatly appreciated :)

EDIT:

I am closer with the following - I am SO close but not sure what little piece I am missing:

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'])

The for r in json_data[x]['rows']: recognizes the correct number of "rows" - whether 2 or 5o - but just returns the values from the 1st dictionary over and over :(

After looping over ['rows'] , you simply need to use the r variable. Use this:

for r in json_data['Generic']['rows']:
    print(r['row1'])
    print(r['row2'])
    print(r['row3'])

Output:

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

The reason you were getting only the first dictionary is - you were using json_data[x]['rows'][0] inside the loop. This [0] will always give you the first item (dictionary) in the 'rows' list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM