Search code examples
pythonjsongoogle-books

python keyError at JSON parsing


I am trying to use Google Books Python API Client. Here is my simple code snippet:

for book in response.get('items', []):
    if not book['volumeInfo']['title'] or not book['volumeInfo']['authors']:
        continue
    else:
        print 'Title: %s, Author: %s' % (book['volumeInfo']['title'], book['volumeInfo']['authors'])

I am trying to get metadata from a list of books based on a keyword. However, It gives me

KeyError: 'authors'

I checked and found out that the JSON response does not have an "authors" field for a specific book. I tried to skip that book with the if else statement above, but it didn't work. How can I avoid from such errors when there isn't a field in the JSON response as I expect?


Solution

  • You can use the dict.get() method to retrieve a default, or you can use membership testing to see if the key is there at all:

    for book in response.get('items', []):
        if 'title' not in book['volumeInfo'] or 'authors' not in book['volumeInfo']:
            continue
        print 'Title: %s, Author: %s' % (book['volumeInfo']['title'], book['volumeInfo']['authors'])