I have a JSON file that looks like this:
{
"authors": [
{
"name": "John Steinbeck",
"description": "An author from Salinas California"
},
{
"name": "Mark Twain",
"description": "An icon of american literature",
"publications": [
{
"book": "Huckleberry Fin"
},
{
"book": "The Mysterious Stranger"
},
{
"book": "Puddinhead Wilson"
}
]
},
{
"name": "Herman Melville",
"description": "Wrote about a famous whale.",
"publications": [
{
"book": "Moby Dick"
}
]
},
{
"name": "Edgar Poe",
"description": "Middle Name was Alan"
}
]
}
I'm using python to get the values of the publications elements.
my code looks like this:
import json
with open('derp.json') as f:
data = json.load(f)
for i in range (0, len (data['authors'])):
print data['authors'][i]['name']+data['authors'][i]['publications']
I'm able to get all the names if i just use a:
print data['authors'][i]['name']
But when I attempt to iterate through to return the publications, I get a keyError. I expect it's because the publications element isn't part of every author.
How can I get these values to return?