Batu Lab NotesPractical developer guides

Explain JSON decode errors as input findings

By Batu ยท English technical notes

Also published in our Blogger archive.

Quick answer

json.loads raises JSONDecodeError, whose line and column identify where parsing stopped.

Example

The malformed object has a missing value after the colon. The handler prints the exception line and column and the assertion fixes the expected diagnostic for that exact fixture. It never edits or rewrites the source string.

import json
source = '{ "name": }'
try:
    json.loads(source)
except json.JSONDecodeError as e:
    result = f'json-error line={e.lineno} column={e.colno}'
assert result == 'json-error line=1 column=11'
print(result)

Expected stdout:

json-error line=1 column=11

Reading the result

Parse location is not a repair instruction: several different intended values could make a malformed document valid. Validate the resulting object shape only after parsing succeeds.

Catch JSONDecodeError specifically instead of a broad exception so filesystem and programmer errors are not mislabeled as malformed input. That distinction keeps a CLI report actionable.

The fixture locks down one known location so a changed parser message does not become the test oracle. The structured exception attributes are the useful stable data.

Sources

- Python json module documentation

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.