python keyError 在 JSON 解析
python keyError at JSON parsing
我正在尝试使用 Google 图书 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'])
我正在尝试使用 Google 图书 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'])