简体   繁体   中英

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?

I suggest you use the get method of dictionaries to pull your keys out. You can set a default incase the key doesn't exist:

book.get('volumeInfo', default=None)

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM