如何在for循环中实现解析JSON的错误检查

时间:2018-03-10 19:43:42

标签: python json python-2.7

我试图从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

1 个答案:

答案 0 :(得分:1)

首先测试一个非空对象:

for season in html:
    images = season['image']
    if not images:
        continue
    test = images['medium']
如果not imagesimages,空字典,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