How can I handle malformed JSON without losing the original file?
Quick answer
Open the JSON file in read mode, then catch json.JSONDecodeError only around json.load(). Report its message, line, and column. Handle OSError separately for file-opening or reading problems, and report text-decoding errors separately too. This reads the original without rewriting it; save any repaired or test output to a different path. [S1]
The question, the details, the next step.
A practical checklist
Open the source with mode
r; keep the original path out of any write operation.Handle
OSErrorseparately for file-access problems, including opening or reading the file.Catch
json.JSONDecodeErroronly aroundjson.load()and report its message, line, and column. [S1]Treat
UnicodeDecodeErroras a text-decoding problem, not a JSON syntax error. [S1]Make and test any correction using a separate copy or output path.
A few more useful answers
Should I print the decoder’s entire document field?
Usually not for a concise error report. The error includes the document, but its message and line and column are a more focused starting point for inspection. [S1]
Does the reported location tell me how to repair the JSON?
No. It helps you find where parsing encountered a problem, but you still need to inspect the content and decide what correction is appropriate.
What if the file opens but its text cannot be decoded?
Report that separately from malformed JSON. Text-decoding errors and JSON syntax errors are distinct failure types. [S1]
Sources
References used for this guide.
- [S1] Python 3.15 json reference: decoding errors and JSONDecodeError details docs.python.org · Checked
