Sub topic 5
Handling malformed JSON with JSONDecodeError
This chapter assumes you can read and write JSON with json.load and json.loads, use with to open files, and write try/except blocks. It covers what happens when the input is not valid JSON and how to report that cleanly.
What the exception tells you
json.loads and json.load raise json.JSONDecodeError when the text does not follow the JSON grammar. It is a subclass of ValueError, so except ValueError also catches it. Catch the specific class when you can. The exception carries these attributes:
msg: a short description of the problem.doc: the full text being parsed.pos: the character offset where parsing failed.linenoandcolno: the same position as a line and column, both counted from 1.
import json
try:
json.loads('{"a": 1,}')
except json.JSONDecodeError as e:
print(e.msg, e.lineno, e.colno)The parser stops at the first error. It never repairs the input or returns partial data.
Common causes
| Input | Why it fails |
|---|---|
| `{"a": 1,}` | Trailing comma |
| `{'a': 1}` | Single quotes instead of double quotes |
| `{a: 1}` | Unquoted key |
| `{"ok": True}` | Python literal. JSON uses `true`, `false`, `null` |
| `{"a": 1} {"b": 2}` | Extra data after the first value |
| `` (empty string) | No value at all |
| `{"a": 1} // note` | Comments are not allowed |
Python 3.13 gave some of these errors more specific messages. For a trailing comma, older versions report a generic "Expecting ..." message and newer ones say the comma is illegal. Don't compare msg against a fixed string in your code. Use lineno and colno for location and show msg only to humans.
Pointing at the problem
A useful error message shows the failing line and marks the column. Split on "\n", not splitlines(). A document that ends right after a newline can fail on a line that splitlines() does not return.
import json
def parse_text(text):
try:
return json.loads(text)
except json.JSONDecodeError as e:
line = text.split("\n")[e.lineno - 1]
print(f"Invalid JSON: {e.msg} (line {e.lineno}, column {e.colno})")
print(line)
print(" " * (e.colno - 1) + "^")
return None
text = '{\n "name": "Ada",\n "langs": ["Python",],\n}'
print(parse_text(text))The output depends on your Python version, as described above. It always names line 3 and puts the caret under the offending character, and the function returns None.
Handling files
Three different failures can happen when you load a file, and each needs its own handler.
import json
from pathlib import Path
def load_json_file(path):
try:
with Path(path).open(encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
raise SystemExit(f"{path}: file not found")
except UnicodeDecodeError:
raise SystemExit(f"{path}: not valid UTF-8")
except json.JSONDecodeError as e:
raise SystemExit(f"{path}:{e.lineno}:{e.colno}: {e.msg}")UnicodeDecodeError happens while the file is being read, before the JSON parser sees any text, so it is not a JSONDecodeError. SystemExit suits a command-line script. In a library, raise your own exception type or let the original propagate.
Valid JSON is not the same as expected JSON
A successful parse only means the syntax is correct. The data can still have the wrong shape: a missing key, a list where you expected an object, or a string where you expected a number. These problems raise KeyError or TypeError later, far from the parsing code. Check the shape right after loading:
import json
data = json.loads('{"name": "Ada"}')
if not isinstance(data, dict) or "retries" not in data:
raise ValueError("config must be an object with a 'retries' key")Exercise
Exercise
A script calls json.loads on a string that ends with "}" followed by another complete object, such as '{"a": 1}{"b": 2}'. What happens, and which exception attributes would you print to help the user find the problem?
Show answer
json.loads raises JSONDecodeError with an "Extra data" message, because it parses the first object and then finds more text. Print e.msg, e.lineno, and e.colno (or e.pos) to show where the extra data starts. If the input is meant to hold many objects, one per line, it is JSON Lines and should be parsed line by line with json.loads on each line.