Cope with JSONDecodeError in requests.get().json() in Python 2 and 3

16 November 2016   3 comments   Python

Suppose you don't know with a hundred percent certainty that an API will respond in with a JSON payload you need to protect yourself.

This is how you do it in Python 3:

import json
import requests

response = requests.get(url)
try:
    print(response.json())
except json.decoder.JSONDecodeError:
    print("N'est pas JSON")

This is how you do it in Python 2:

import requests

response = requests.get(url)
try:
    print response.json()
except ValueError:
    print "N'est pas JSON"

Here's how you make the code work across both:

import json
import requests

try:
    from json.decoder import JSONDecodeError
except ImportError:
    JSONDecodeError = ValueError

response = requests.get(url)
try:
    print(response.json())
except JSONDecodeError:
    print("N'est pas JSON")

Comments

Jack
My immediate thought was why not do something like this, but then I thought for the sake of repetition and clarity your solution makes more sense.

import json
import requests

response = requests.get(url)
try:
    print(response.json())
except (json.decoder.JSONDecodeError, ValueError):
    print("N'est pas JSON")
Florian
JSONDecodeError is a subclass of ValueError, so I'd expect a simple `except ValueError:` to work fine on both versions.
Peter Bengtsson
Cool! I didn't know that. But it makes perfect sense.
Granted there are benefits to using specific exceptions to avoid "over swallowing" errors if you cover multiple lines.
Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
How to deploy a create-react-app 04 November 2016
Next:
Using Fanout.io in Django 13 December 2016
Related by Keyword:
Msgpack vs JSON (with gzip) 19 December 2017
Fastest Redis configuration for Django 11 May 2017
Best practice with retries with requests 19 April 2017
Fastest way to download a file from S3 29 March 2017
json-schema-reducer 02 August 2016
Related by Text:
HTML Tree on Hacker News 18 May 2014
YouTube - Nigella's XXXmas 19 December 2008
How and why to use django-mongokit (aka. Django to MongoDB) 08 March 2010
How to track Google Analytics pageviews on non-web requests (with Python) 03 May 2016
hashin 0.7.0 and multiple packages 30 August 2016