Skip to content

How to Fix json.JSONDecodeError in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix json.JSONDecodeError in Python. We cover key concepts, practical examples, and best practices.

Python raises json.JSONDecodeError when trying to parse a string that does not contain valid JSON.

The Wrong Way

import json

data = '{"name": "Alice", "age": }'
parsed = json.loads(data)
print(parsed)

This produces:

Traceback (most recent call last):
  File "script.py", line 3, in <module>
    parsed = json.loads(data)
json.JSONDecodeError: Expecting value: line 1 column 30 (char 29)

The Right Way

Validate and fix the JSON string before parsing:

import json

data = '{"name": "Alice", "age": 30}'
parsed = json.loads(data)
print(parsed)

Output:

{'name': 'Alice', 'age': 30}

Step-by-Step Fix

1. Check for empty responses

import json

response_text = ""  # empty response
try:
    data = json.loads(response_text)
except json.JSONDecodeError:
    print("Empty or invalid JSON response")
    data = {}

2. Use a validation function

import json

def safe_json_loads(text):
    try:
        return json.loads(text)
    except (json.JSONDecodeError, TypeError) as e:
        print(f"JSON decode error: {e}")
        return None

result = safe_json_loads('{"key": "value"}')
print(result)

3. Validate JSON with online tools

Paste the failing JSON string into a JSON validator to find syntax errors.

4. Check for BOM markers

import json

with open('data.json', 'r', encoding='utf-8-sig') as f:
    data = json.load(f)

5. Use strict=False (rarely needed)

import json

# This allows some non-standard JSON features
data = json.loads('{"key": "value"}', strict=False)

Prevention Tips

  • Always validate JSON with json.loads() inside a try-except block.
  • Check that API responses are not empty before parsing.
  • Use json.dumps() to serialize Python objects to valid JSON.
  • Validate JSON files with command-line tools like python3 -m json.tool file.json.
  • Handle both JSON and non-JSON responses from external APIs gracefully.

Common Mistakes with json decode

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the most common cause of JSONDecodeError?

The most common cause is an empty or HTML response when an API returns an error page instead of JSON. Always check the HTTP status code before parsing.

How do I find the exact position of the JSON error?

The error message includes a column number. Load the string in a JSON validator and it will highlight the exact position of the syntax error.

Can JSONDecodeError happen with single quotes?

Yes. JSON requires double quotes for strings. json.loads("{'key': 'value'}") raises JSONDecodeError. Use json.loads('{"key": "value"}') instead.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro