0

I am trying to parse this JSON from the tvmaze api. The JSON that is returned has one object as None. This is causing the for loop to break. How can I catch this error and skip it?

The simple code looks like this:

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

This results in this error:

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

I can see that if I print imagesthe result is:

{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

I have tried multiple versions of if 'medium' not in images, but I get this error:

TypeError: argument of type 'NoneType' is not iterable
1
  • Your if 'medium' not in images: line is not present in the code you show. Commented Mar 10, 2018 at 19:49

1 Answer 1

1

Just test for a non-empty object first:

for season in html:
    images = season['image']
    if not images:
        continue
    test = images['medium']

not images is true if images is None, an empty dictionary, 0, or any other object that tests as false.

You could also explicitly test for `None:

if images is None:
    continue

or you could invert the tests:

if images and 'medium' in images:
    #  there is a medium image

or

if images is not None and 'medium' in images:
    #  there is a medium image
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.