Back to blog
Tutorials9 min read

How to Parse JSON in Python: loads, load & Common Errors

A practical guide to parsing JSON in Python: json.loads vs json.load, the Python-to-JSON type mapping, serializing with json.dumps, and how to fix JSONDecodeError and other common parsing mistakes.

By Saifur Rahman Shochib

Parsing JSON is one of the first things you do in almost any Python project that touches an API, a config file, or a dataset. The standard library makes it a one-liner — but the difference between json.loads and json.load, the way Python maps JSON types, and the errors a malformed payload throws all trip people up. This guide covers everything you need to read, parse, and write JSON reliably in Python, plus how to debug the errors when input is not as clean as you hoped.

The json module

Python ships with a built-in json module, so there is nothing to install. It exposes four core functions arranged in two pairs: loads and load for reading (deserializing) JSON, and dumps and dump for writing (serializing) Python objects to JSON. The s in loads and dumps stands for string — those work with strings, while load and dump work with files.

json.loads() — parse a JSON string

Use json.loads() when you already have JSON as a string, for example the text of an HTTP response. It returns native Python objects: a JSON object becomes a dict, an array becomes a list, and so on. For instance, json.loads('{"name": "Ada", "age": 36}') returns a dictionary you can index with square brackets.

If you are using the popular requests library, response.json() is a convenience wrapper that calls json.loads on the response body for you.

Parse a JSON string with json.loadspython
import json
data = json.loads('{"name": "Ada", "age": 36}')
data["name"]   # "Ada"

json.load() — parse a JSON file

Use json.load() to read JSON directly from a file-like object. The idiomatic pattern is to open the file in a with block, which guarantees it is closed even if an error occurs: with open('data.json', encoding='utf-8') as f: data = json.load(f). Specifying encoding='utf-8' avoids platform-dependent encoding surprises.

A frequent beginner error is passing a filename or a file object to json.loads() (with the s). That fails because loads expects a string of JSON, not a file. Match the function to your input: a string needs loads, a file needs load.

Parse a file with json.loadpython
with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

How Python maps JSON types

  • JSON object becomes a Python dict
  • JSON array becomes a Python list
  • JSON string becomes a str
  • JSON number (integer) becomes an int
  • JSON number (decimal) becomes a float
  • JSON true / false become True / False
  • JSON null becomes None

Writing JSON back out: dumps and dump

json.dumps() turns a Python object into a JSON string; json.dump() writes it straight to a file. Both accept useful options: indent=2 pretty-prints the output, sort_keys=True orders keys alphabetically, and ensure_ascii=False keeps non-Latin characters and emoji readable instead of escaping them to unicode sequences.

When an object is not serializable by default — such as a datetime or a Decimal — pass a default function that tells json how to convert it, or transform the value to a string or number first.

Handling JSONDecodeError

When the input is not valid JSON, Python raises json.JSONDecodeError, a subclass of ValueError. The exception is precise: it reports the message, line, and column of the failure, for example 'Expecting property name enclosed in double quotes: line 3 column 5'. Wrap parsing in a try/except to handle bad input gracefully instead of crashing.

Catch both the decode error and, for file reads, FileNotFoundError: try: data = json.load(f) except json.JSONDecodeError as e: handle the malformed JSON, except FileNotFoundError: handle the missing file. Logging the line and column from the exception makes malformed payloads quick to fix.

Handle malformed input preciselypython
try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print(f"Invalid JSON at line {e.lineno}, col {e.colno}: {e.msg}")

Common pitfalls and how to avoid them

  • Single quotes — JSON requires double quotes around keys and strings. A Python dict printed with str() uses single quotes and is not valid JSON; use json.dumps to produce real JSON.
  • Trailing commas — valid in Python literals but illegal in JSON, and a very common cause of JSONDecodeError.
  • NaN and Infinity — Python's json accepts them by default but they are not standard JSON, so downstream consumers may reject the output. Pass allow_nan=False to catch this early.
  • Non-serializable types — datetimes, sets, and Decimals raise TypeError on dump; convert them or supply a default function.
  • Very large files — json.load reads everything into memory; for files over roughly 100 MB consider a streaming parser or the line-by-line JSONL approach.

Validate before you parse

When you are debugging a payload from an API or an LLM, it helps to confirm the JSON is well-formed before you write code around it. Paste it into a JSON validator to get the exact line and column of any syntax error, use a formatter to make nested structure readable, or run it through a repair tool if it arrived with trailing commas or code fences. Catching the problem in the data is faster than catching it in a stack trace.

Frequently asked questions

What is the difference between json.loads and json.load?

json.loads parses JSON from a string; json.load parses JSON from a file-like object. The trailing s means string. Use loads for an in-memory string (like an API response body) and load when reading directly from an open file.

How do I fix a JSONDecodeError in Python?

Read the error — it tells you the exact line and column. The usual causes are single quotes instead of double quotes, trailing commas, unquoted keys, or truncated data. Fix the source JSON (a validator pinpoints the spot), and wrap parsing in a try/except json.JSONDecodeError for resilience.

How do I parse JSON from an API in Python?

If you use the requests library, call response.json(), which parses the response body for you. Otherwise pass the response text to json.loads(). Always handle the case where the body is empty or not JSON.

How do I pretty-print JSON in Python?

Pass indent to json.dumps, for example json.dumps(data, indent=2). Add sort_keys=True to order keys and ensure_ascii=False to keep non-ASCII characters human-readable.

Why does my JSON have single quotes and fail to parse?

That is usually a Python dict converted with str(), not real JSON — JSON mandates double quotes. Produce valid JSON with json.dumps(obj) instead of str(obj) or print(obj).

Related tools

Try these tools

Keep reading

Related guides