我试图从tvmaze api解析这个JSON。返回的JSON有一个对象None
。这导致for
循环中断。如何捕获此错误并跳过它?
简单代码如下所示:
import requests,re,json
url = "http://api.tvmaze.com/shows/1/seasons"
html = requests.get(url).json()
for season in html:
images = season['image']
test = images['medium']
print test
这会导致此错误:
Traceback (most recent call last):
File "C:/Python27/test_maze.py", line 7, in <module>
if 'medium' not in images:
TypeError: argument of type 'NoneType' is not iterable
我可以看到,如果我print images
结果是:
{u'medium': u'http://static.tvmaze.com/uploads/images/medium_portrait/24/60941.jpg', u'original': u'http://static.tvmaze.com/uploads/images/original_untouched/24/60941.jpg'}
{u'medium': u'http://static.tvmaze.com/uploads/images/medium_portrait/24/60942.jpg', u'original': u'http://static.tvmaze.com/uploads/images/original_untouched/24/60942.jpg'}
None
我尝试了if 'medium' not in images
的多个版本,但是我收到了这个错误:
TypeError: argument of type 'NoneType' is not iterable
答案 0 :(得分:1)
首先测试一个非空对象:
for season in html:
images = season['image']
if not images:
continue
test = images['medium']
如果not images
为images
,空字典,None
或任何other object that tests as false,则 0
为真。
你也可以明确地测试`None:
if images is None:
continue
或者你可以反转测试:
if images and 'medium' in images:
# there is a medium image
或
if images is not None and 'medium' in images:
# there is a medium image