Sub topic 5
Handling malformed JSON with JSONDecodeError
This chapter assumes you can already call json.load, json.loads, json.dump, and json.dumps. It also assumes you know try/except, how to open files with with, and that a Python str holds text while bytes holds raw data. Here you will learn what json.JSONDecodeError tells you, how to catch it at the right level, and which failures it does not cover.
What JSONDecodeError is
json.loads and json.load raise json.JSONDecodeError when the text is not valid JSON. The class inherits from ValueError, so except ValueError also catches it. Catching json.JSONDecodeError is more precise, because other ValueError sources (such as a failed int() call in your own code) stay visible.
The exception carries the location of the problem:
| Attribute | Meaning |
|---|---|
| `msg` | The unformatted description, such as "Expecting value" |
| `doc` | The full text that was being parsed |
| `pos` | Zero-based character index where parsing failed |
| `lineno` | Line number, starting at 1 |
| `colno` | Column number, starting at 1 |
Printing the exception itself gives a combined message such as Expecting value: line 1 column 1 (char 0).
import json
try:
json.loads('{"a": 1,}')
except json.JSONDecodeError as e:
print(e.msg, e.lineno, e.colno, e.pos)Common causes
Most malformed JSON comes from people or programs that write something JSON-like but not JSON.
| Input | Problem |
|---|---|
| `{"a": 1,}` | Trailing comma. JSON allows none. |
| `{'a': 1}` | Single quotes. JSON strings and keys use double quotes only. |
| `{a: 1}` | Unquoted key. |
| `{"a": 1} // note` | Comments are not part of JSON. |
| `{"ok": True}` | Python's `True`, `None`, or `False` instead of `true`, `null`, or `false`. This usually means someone wrote `str(dict)` instead of `json.dumps`. |
| `{"a": 1} {"b": 2}` | Two documents in one string. This raises "Extra data". |
| `{"a": 1` | Truncated input, often from an interrupted download or write. |
| Empty string | There is nothing to parse, so you get "Expecting value" at position 0. |
| A line break inside a string | Raw control characters must be escaped as `\n`. |
Empty input is common in practice. A file that was just created, or an HTTP response with no body, produces Expecting value: line 1 column 1 (char 0). Decide whether that means "no data yet" or "broken", and handle it on purpose.
Reading the error position
A message like "line 3 column 22" is not very helpful in a large document. A small helper can print the offending line with a pointer under the column:
import json
def show_error(e: json.JSONDecodeError) -> str:
lines = e.doc.splitlines() or [""]
line = lines[e.lineno - 1] if e.lineno <= len(lines) else ""
pointer = " " * (e.colno - 1) + "^"
return f"{e.msg} (line {e.lineno}, column {e.colno})\n{line}\n{pointer}"
text = '{\n "name": "Ada",\n "langs": ["Python" "C"]\n}'
try:
json.loads(text)
except json.JSONDecodeError as e:
print(show_error(e))The output points at the second string, where a comma was expected:
Expecting ',' delimiter (line 3, column 22)
"langs": ["Python" "C"]
^The guard on lines matters. When the input is empty, or ends with a newline and the error sits at the very end, lineno can be larger than the number of lines that splitlines() returns. Without the guard, your error reporter would crash with an IndexError.
The position is where the parser noticed the problem, which is not always where the mistake is. A missing closing quote, for example, usually surfaces later in the document. Look at the text just before the reported position as well.
For very large documents, do not print e.doc or log it in full. Slice around the position instead:
snippet = e.doc[max(0, e.pos - 30): e.pos + 30]Catching the error at the right level
Put the try block around the parse call and the file access that feeds it, and convert low-level errors into one error type that your own code understands. The function below handles a config file:
import json
from pathlib import Path
class ConfigError(Exception):
"""Raised when a config file cannot be used."""
def load_config(path):
path = Path(path)
try:
with path.open(encoding="utf-8-sig") as f:
data = json.load(f)
except FileNotFoundError as e:
raise ConfigError(f"{path} does not exist") from e
except UnicodeDecodeError as e:
raise ConfigError(f"{path} is not valid UTF-8") from e
except json.JSONDecodeError as e:
raise ConfigError(
f"{path}: {e.msg} at line {e.lineno}, column {e.colno}"
) from e
if not isinstance(data, dict):
raise ConfigError(f"{path}: expected an object, got {type(data).__name__}")
retries = data.get("retries", 3)
if not isinstance(retries, int) or isinstance(retries, bool):
raise ConfigError(f"{path}: 'retries' must be an integer")
return data
Path("bad.json").write_text('{"retries": 3,}', encoding="utf-8")
try:
load_config("bad.json")
except ConfigError as e:
print("Config problem:", e)Several details in this function are deliberate:
encoding="utf-8-sig"reads UTF-8 and silently removes a byte order mark (BOM), an invisible marker some Windows editors put at the start of a file. With plainutf-8, a BOM reaches the parser and raises aJSONDecodeErrorsaying the BOM is unexpected.raise ... from ekeeps the original traceback attached, so debugging still shows the exact parse failure.- The shape check after parsing exists because valid JSON can still be the wrong thing. A file containing
[1, 2]or"hello"parses without error but is not an object. isinstance(retries, bool)is needed becauseboolis a subclass ofintin Python, sotruein the file would otherwise pass as an integer.
The next diagram shows where each failure originates.
Failures that are not JSONDecodeError
Not every bad input produces JSONDecodeError:
- Wrong argument type.
json.loads(None)andjson.loads({"a": 1})raiseTypeError.json.loadsacceptsstr,bytes, andbytearray. A common mistake is passing a file object toloadswhen you meantload. This is a bug in your code, so let it propagate instead of reporting it as bad data. - Bad bytes.
UnicodeDecodeErrorhappens before the parser runs, when the file is not in the encoding you declared. It is also aValueErrorsubclass, so a broadexcept ValueErrorwould hide the difference between "wrong encoding" and "wrong syntax". - Wrong shape. A missing key gives
KeyError, and a wrong type givesTypeErrororAttributeError, but only when you use the data later. Validating right after parsing puts the failure next to its cause.
Strictness gotchas
Python's parser is a little more permissive than the JSON standard. By default, json.loads accepts NaN, Infinity, and -Infinity, which are not valid JSON. Other parsers will reject files you produce with them. The parse_constant hook lets you reject them when reading:
import json
def reject_constant(name):
raise ValueError(f"Non-standard JSON constant: {name}")
print(json.loads('{"x": NaN}'))
try:
json.loads('{"x": NaN}', parse_constant=reject_constant)
except ValueError as e:
print(e)The first call prints {'x': nan}. The second raises your ValueError, which passes through unchanged and is not wrapped in JSONDecodeError. When writing, json.dumps(..., allow_nan=False) makes NaN raise a ValueError instead of producing non-standard output.
Duplicate keys are also accepted. json.loads('{"a": 1, "a": 2}') returns {'a': 2}, and the first value is lost silently. If duplicates indicate a bug in your data source, pass an object_pairs_hook that checks for them.
Partial failure in line-based data
When each line of a file is its own JSON document (the JSON Lines format), one bad line should often not stop the whole run. Parse line by line, collect failures with their line numbers, and report them at the end:
import json
def read_jsonl(path):
good, bad = [], []
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
good.append(json.loads(line))
except json.JSONDecodeError as e:
bad.append((number, e.msg))
return good, bad
with open("events.jsonl", "w", encoding="utf-8") as f:
f.write('{"id": 1}\n{"id": 2,}\n\n{"id": 3}\n')
records, errors = read_jsonl("events.jsonl")
print(len(records), "ok")
print("bad lines:", [n for n, _ in errors])This prints 2 ok and bad lines: [2]. The line number here comes from the file, not from e.lineno, because each loads call sees only a one-line string where lineno is always 1.
Whether to skip, stop, or quarantine bad records depends on the job. For an audit log, dropping records silently is dangerous. Count the failures and fail loudly if the count passes a threshold.
Do not repair JSON silently
It is tempting to fix the input by stripping trailing commas with a regex, or by replacing single quotes with double quotes. These repairs break on valid content, such as an apostrophe inside a string, and they hide the real problem, which is a producer writing bad JSON. Prefer these options, in order:
- Fix the producer, and use
json.dumpsinstead of building strings by hand or callingstr()on a dict. - Reject the input with a clear error that includes the line and column.
- If you control the source and know it emits Python literals, use
ast.literal_evalon that specific input and document why.
Exercises
Exercise
A function calls json.loads(response_text) and wraps it in except json.JSONDecodeError. In production it sometimes crashes with TypeError. What is the most likely cause, and should you catch it?
Show answer
response_text was probably None or another non-string (for example an empty body returned as None). loads accepts only str, bytes, and bytearray, and passing anything else raises TypeError. This is a bug in the calling code, not bad data, so you should fix the code that produces the value or check for None explicitly instead of catching TypeError broadly.
Exercise
Write a function parse_or_default(text, default) that returns the parsed value, or default when text is not valid JSON, and prints "line L, column C" for the error. Why is lineno useful here but pos less so for a person reading a message?
Show answer
Example:
def parseordefault(text, default):
try:
return json.loads(text)
except json.JSONDecodeError as e:
print(f"line {e.lineno}, column {e.colno}")
return default
Editors show line and column numbers, so a person can jump straight to the spot. pos is a character offset from the start of the whole text, which is hard to locate by hand in a multi-line document. It is more useful in code, for slicing e.doc around the failure.
Exercise
A config file saved by a Windows editor fails to load with an error about a BOM, although the JSON looks correct. What one-argument change to open fixes it, and why?
Show answer
Open the file with encoding="utf-8-sig". This codec removes the byte order mark at the start of the file, so the parser sees only the JSON text. With plain utf-8, the BOM character stays in the string and the parser rejects it.