简体   繁体   中英

iterate through a nested list to get a specific value using python

I have a json file where I'm trying to pull just "code" from multiple "areas"

I am able to pull the codes individually, but I feel like there should be a for loop I can write to iterate over every 'area' automatically as I won't always just have 3 areas.

I have tried multiple variations of the below nested loop but I just can't get it to iterate

for areas in data:
   for area in areas:
      print(area['code']

Current python code:

import json

with open('areas.json') as f:
    data = json.load(f)


    print(data['areas'][0]['area']['code'])
    print(data['areas'][1]['area']['code'])
    print(data['areas'][2]['area']['code'])

JSON file:

"areas": [
      {
         "slotId": "slot1",
         "area": {
            "id": "southern",
            "code": "southern",
            "label": "southern area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      },
      {
         "slotId": "slot2",
         "area": {
            "id": "easter",
            "code": "eastern",
            "label": "eastern area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      },
      {
         "slotId": "slot3",
         "area": {
            "id": "western",
            "code": "western",
            "label": "western area",
            "featureToggles": [],
            "featureChoices": []
         },
         "editable": true,
         "areaCategoryId": null
      }

The expected results is that the 'code' prints out for each area. Which it does correctly. However I want to iterate through it without having to add a new line every time as that's just ridiculous and tedious.

Access data['areas'] which is a list, then iterate over it to get the individual area objects

with open('areas.json') as f:
    data = json.load(f)

    for area in data['areas']:
        print(area['area']['code'])

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