API Navigator Logo

Python Handle JSON Decode Error

Author: Newtum

This guide explains how to gracefully handle a `JSONDecodeError` when an API response is expected to be JSON but is not, or is malformed.

The Problem: Invalid JSON

Calling `.json()` on a response that does not contain valid JSON will raise a `requests.exceptions.JSONDecodeError`. This can happen if the server returns an HTML error page, plain text, or malformed JSON.

Handling the Exception

You should wrap the `response.json()` call in a `try...except` block to catch the `JSONDecodeError` and handle it, for example by inspecting the raw text of the response.

import requests

# This URL returns a normal HTML page, not JSON
url = 'https://httpbin.org/html'

response = requests.get(url)

if response.status_code == 200:
    try:
        data = response.json()
        print("JSON data:", data)
    except requests.exceptions.JSONDecodeError:
        print("Failed to decode JSON.")
        print("Response was not in JSON format.")
        print("Raw text response (first 100 chars):")
        print(response.text[:100] + '...')
else:
    print(f"Request failed with status code {response.status_code}")