Report a JSONDecodeError line and column without printing the source
Also published in our primary archive.
Report a JSONDecodeError line and column without printing the source
To report a JSONDecodeError location without printing JSON source, catch the exception and format only lineno and colno. Do not include error.doc or stringify data you do not intend to expose. The parser retains the document in error.doc, so printing that attribute would reveal the fixture’s values.
The multiline input deliberately omits the comma after the token member. The unsafe variable in the example models the tempting diagnostic path: it contains keep-private. Nothing prints it. Instead, the corrected report is constructed from the two numeric location attributes and yields invalid JSON at line 3, column 3. Assertions verify both the exact location and that the sensitive fixture value is absent from the report. This handles a syntax error; it does not validate the semantics of a JSON document that parses successfully.
The official JSONDecodeError documentation defines doc, lineno, and colno; JSONDecodeError was added in Python 3.5. The code itself uses no APIs newer than Python 3.5, although Python 3.6+ is a practical baseline for current maintenance.
AI assistance disclosure: this article was drafted with AI assistance and uses a synthetic document rather than user data.
import json
source = '{\n "token": "keep-private"\n "enabled": true\n}'
try:
json.loads(source)
except json.JSONDecodeError as error:
unsafe = error.doc
report = "invalid JSON at line {}, column {}".format(
error.lineno, error.colno
)
assert "keep-private" in unsafe
assert "keep-private" not in report
assert report == "invalid JSON at line 3, column 3"
print(report)
invalid JSON at line 3, column 3