I have this .JSON file that tells what food there will be during the week in our school.(Sorry it's in Swedish)
Here is the JSON file
{
"feedbackAllowed": "True",
"weeks": [
{
"days": [
{
"date": 1647820800,
"items": [
"Korv Stroganoff serveras med ris",
"Vegetarisk Stroganoff med sojakorv serveras ris"
]
},
{
"date": 1647907200,
"items": [
"Pasta serveras med laxsås",
"Vegetarisk pastasås"
]
},
{
"date": 1647993600,
"items": [
"Morotslasagne med keso och soltorkad tomat",
"Kökets klimatsmarta rätt ( vegetarisk lasagne)"
]
},
{
"date": 1648080000,
"items": [
"Het kycklingsoppa serveras med mjukt bröd och ost samt frukt",
"Vegetarisk nudelsoppa serveras med mjukt bröd och ost samt frukt"
]
},
{
"date": 1648166400,
"items": [
"Quorngryta med chili serveras med ris",
"Kökets klimatsmarta rätt"
]
}
],
"number": 12,
"year": 2022
}
],
"school": {
"URLName": "XXX",
"id": 000,
"district": {
"province": {
"URLName": "XXX",
"id": 000,
"name": "XXX"
},
"URLName": "XXX",
"id": 000,
"name": "000"
},
"name": "000"
},
"id": 000,
"bulletins": [
{
"text": "XXX"
}
]
}
What I am looking for is a way to only print out the "items"(all of them) from the JSON file. I have watched many tutorials and i keep getting errors like:
TypeError: '_io.TextIOWrapper' object is not callable
etc.
i tried using this
import json
with open('filename.json', 'r') as input:
obj = json.load(input)
#make it a string the item is the first one
print(str(obj['items']))
but i got this error:
KeyError: 'items'
CodePudding user response:
You have to loop over all the weeks and days.
for week in obj['weeks']:
for day in week['days']:
print(day['items'])
CodePudding user response:
So the items
property you're trying to access is nested deeply within the JSON structure. As Barmar has correctly pointed out, you'll have to first step inside the weeks array, and then the days arrays within each week in order to access the objects that has "items" property.
obj > weeks > days > items
For loops will be your best friend to print out these properties.
CodePudding user response:
I was able to access them like this. Just navigating down the dicts and lists
for i in range(len(obj['weeks'][0]['days'])):
print(obj['weeks'][0]['days'][i]['items'])