JSON解析时出现python键错误

JSON解析时出现python键错误,python,json,google-books,Python,Json,Google Books,我正在尝试使用谷歌图书Python API客户端。以下是我的简单代码片段: 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'],

我正在尝试使用谷歌图书Python API客户端。以下是我的简单代码片段:

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'])
我试图从基于关键字的书籍列表中获取元数据。然而,它给了我

KeyError: 'authors'
我检查并发现JSON响应没有特定书籍的authors字段。我试图用上面的if-else语句跳过那本书,但没用。当JSON响应中没有预期的字段时,如何避免此类错误

我建议您使用字典的get方法取出您的密钥。如果密钥不存在,可以设置默认值:

book.get('volumeInfo', default=None)
您可以使用dict.get方法检索默认值,也可以使用成员资格测试查看密钥是否存在:

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