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

16 November 2016   3 comments   Python

Powered by Fusion×

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")
Follow @peterbe on Twitter

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:
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
How to track Google Analytics pageviews on non-web requests (with Python) 03 May 2016
Related by Text:
json-schema-reducer 02 August 2016
jsonpprint - a Python script to format JSON data nicely 21 November 2010
From Postgres to JSON strings 12 November 2013
Best practice with retries with requests 19 April 2017
To JSON, Pickle or Marshal in Python 08 May 2009