-1

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?

didjit
  • 9
  • 1
  • 3
  • just check if key is present before accessing.`if 'publications' in (data['authors'][i])` – mad_ Oct 25 '18 at 18:57
  • As an aside, don't use `for i in range (0, len (data['authors']))`, just use `for author in data['authors']` and you can print `author['name'] + author['publications']`, you almost *never* want `for i in range(len(some_object))` unless you actually want the indices – juanpa.arrivillaga Oct 25 '18 at 19:04
  • It works for the publications, but not for the books. Not understanding why. – didjit Oct 25 '18 at 21:54

2 Answers2

0

You can do a

if 'publications' in data['authors'][i].keys()

to check if the publications key exists beforehand

IanQ
  • 1,831
  • 5
  • 20
  • 29
0

you can check it by

 if 'publications' in (data['authors'][i])
PushpikaWan
  • 2,437
  • 3
  • 14
  • 23