Reputation: 17
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.
Upvotes: 0
Views: 51
Reputation: 21275
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'])
Upvotes: 1