Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

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]

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I want to load a JSON file in Python, but a syntax mistake should not make me overwrite or lose the original. What is the safe pattern?

Geez

Open the file in read mode and pass the open file object to json.load(). Keep the json.JSONDecodeError handler narrowly around that call, and handle OSError separately for problems opening or reading the file. That way, a file-access failure is not reported as a JSON syntax problem. The JSON decoder error provides a message, line, and column you can show to help locate malformed content. [S1]

For example, using [sample.json] as a placeholder path:

import json

path = "[sample.json]"

try:
    with open(path, "r", encoding="utf-8") as source:
        try:
            data = json.load(source)
        except json.JSONDecodeError as exc:
            print(
                f"Invalid JSON: {exc.msg} "
                f"(line {exc.lineno}, column {exc.colno})"
            )
        except UnicodeDecodeError as exc:
            print(f"Could not decode the file as text: {exc}")
        else:
            print("JSON loaded successfully")
except OSError as exc:
    print(f"Could not access the file: {exc}")

This reads the source; it does not write or repair it. The separate UnicodeDecodeError handler matters because text-decoding failure is different from a JSON syntax error. [S1]

Follow-up question

Why not put the whole thing inside except Exception and print “bad JSON” if anything goes wrong?

Geez

Because different failures call for different next steps. A missing file, permissions problem, or other file-access failure is not the same as malformed JSON. A broad handler can blur that distinction and tell you to fix JSON when the file could not be read. Keep the syntax-error handler around json.load() and handle OSError separately for file access. [S1]

The example also treats text-decoding failure separately. It does not claim every input problem is a syntax error, and it avoids printing the full document. For a small local debugging sample, the exception message and location are a focused starting point.

Follow-up question

What should I do with the line and column, and how do I check whether the original stayed unchanged?

Geez

Use the reported line and column to inspect that area of the file in a text editor. They identify where the decoder encountered the problem; they do not automatically repair the document or prove that the preceding text is the only issue. The decoder error also exposes a position and the document, but you usually need not print the entire document to make a useful report. [S1]

To protect the original, keep this workflow read-only: run the parser, inspect the reported location, and make any proposed correction in a separate copy. If you want to test repaired JSON, save that test as a different file, such as [sample-fixed-test.json], and parse that copy. Do not add a write step targeting the original path.

Follow-up question

Can you give me a simple report format I can reuse when a parse fails?

Geez

For a malformed file, make the report actionable but concise. For example, assuming the file is named [sample.json], a hypothetical error report could be:

File: [sample.json]
Problem: Invalid JSON — [decoder message]
Location: line [line number], column [column number]
Next step: Inspect this location; make any test correction in a separate copy.

Those bracketed values are placeholders, not a claim about your file. Use the decoder’s actual msg, lineno, and colno values in your program. [S1] For file-access and text-decoding failures, report the corresponding problem type instead of using the “Invalid JSON” label. This keeps the report useful without suggesting that the source was changed or that parsing itself found a repair.

A practical checklist

  • Open the source with mode r; keep the original path out of any write operation.

  • Handle OSError separately for file-access problems, including opening or reading the file.

  • Catch json.JSONDecodeError only around json.load() and report its message, line, and column. [S1]

  • Treat UnicodeDecodeError as 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.

  1. [S1] Python 3.15 json reference: decoding errors and JSONDecodeError details
    docs.python.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work