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

16 November 2016   4 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.
dmtucker
simplejson.scanner.JSONDecodeError in py2

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:
Fancy linkifying of text with Bleach and domain checks (with Python) 10 October 2018
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
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010