0

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.

1 Answer 1

1

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'])
Sign up to request clarification or add additional context in comments.

3 Comments

So I modified my code and now I'm getting a KeyError: 'area'. It states I'm getting it on line 8 which for me would be the above print statement ``` print(area['area']['code']) ```
According to your example, each of your objects are supposed to have area key in them. Perhaps, that is not the case?
The above code is correct, I had a typo on my end. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.