How do I fix invalid JSON automatically?

Dark navy cover card with the title 'How do I fix invalid JSON automatically?' in white and a green accent bar

To fix invalid JSON automatically, run it through a repair library such as jsonrepair, then validate the output and compare it with the original. Repairs like swapping single quotes or stripping trailing commas are safe. Repairs that close brackets around truncated data are not, so check those by hand.

What can a tool fix in invalid JSON automatically?

A repair tool can fix most syntax mistakes that a person or a script makes, as long as the intended data is still in the text. The jsonrepair README lists what it handles, including:

  • Missing quotes around keys, missing commas and missing closing brackets.
  • Single quotes and curly "smart" quotes, replaced with regular double quotes.
  • Trailing commas and // or /* */ comments, stripped.
  • Python constants None, True and False, turned into null, true and false.
  • Markdown fences like ```json, which is handy for LLM output.
  • JSONP wrappers like callback({ ... }), and MongoDB types like NumberLong(2).
  • Newline-delimited JSON, turned into one array.
  • Truncated JSON.

The README's own example turns {name: 'John'} into {"name": "John"}. When it meets something it can't solve, the function throws a JSONRepairError instead of returning a guess.

How to fix invalid JSON automatically, step by step

The safe workflow is: read the error, repair, re-validate, then diff. Skipping the last two steps is how bad data ends up in production.

  1. Read the parser error first. It tells you what kind of break you have. In Firefox, JSON.parse('{"foo": 1,}') fails with JSON.parse: unexpected character at line 1 column 14 of the JSON data, according to MDN's JSON.parse error reference. Python's json module raises JSONDecodeError, which carries lineno, colno and pos for the same purpose.
  2. Repair a copy. Install with npm install -g jsonrepair and run jsonrepair broken.json --output fixed.json. In code, call jsonrepair(text) inside a try block.
  3. Re-validate the output. Parse fixed.json with the same parser your app uses. A clean parse means the syntax is valid, nothing more.
  4. Format both files and diff them. Pretty-print the original and the repaired version with the same indentation, then compare. Every change the tool made should be one you'd have made yourself.

For step 1 without installing anything, the OnlineViewer Dev JSON validator shows the JSON.parse error for pasted text, and the tool code makes no network requests.

Which automatic repairs are safe and which change your data?

Repairs that only change punctuation are safe; repairs that fill in or drop content need a human check. The tool can make the text parse, but it can't know what the data was supposed to be.

Problem What the repair does Risk
Single or curly quotes Replaces them with " Low
Trailing comma Removes it Low
Comments Removes them Low: the notes are gone, the data isn't
Unquoted keys Adds quotes Low
None, True, False Becomes null, true, false Low
Missing comma between items Inserts one Medium: check two values weren't meant to be one string
Missing closing bracket Adds it at the end Medium: nesting can come out wrong
Truncated document Closes everything open High: the missing records stay missing
Ellipsis like [1, 2, 3, ...] Strips it High: the list was a sample, not the data

Say a log line cut off at a size limit ends with {"id": 7, "items": [{"sku": "A1"}, {"sk. Repair closes the open string, object, array and outer object, and the result parses. But the order now looks like it had one item, and nothing in the output says otherwise. If you've seen Unexpected end of JSON input, this is the same truncation, just hidden instead of reported.

When you shouldn't repair at all

If the JSON is meant to be config that people edit, change the parser instead of the file. Hand-written files often have comments and trailing commas on purpose. JSON5 allows single and multi-line comments, a single trailing comma in objects and arrays, and single-quoted strings, and every valid JSON file is also valid JSON5. My post on JSON vs JSON5 vs JSONC covers which tools read which format.

The other case is data from your own code. If a service keeps producing single-quoted keys, the fix belongs in that service: it's printing a Python dict or a JavaScript object instead of calling a real serializer. Repairing downstream hides the bug. The rules being broken are explained in why JSON requires double quotes and why JSON doesn't allow trailing commas.

My take: auto-repair belongs in one-off cleanup and on LLM output you were going to check anyway. Keep it out of any pipeline that writes to a database unless you log every repaired input, so someone can see what changed.

What OnlineViewer Dev can and can't do here

OnlineViewer Dev validates and cleans JSON, but it doesn't have an automatic repair feature. The validator reports the parser error so you can fix the line yourself. The JSON unescape tool handles one specific break: double-escaped, stringified JSON like {\"id\": 1}. The formatter and diff checker help with step 4.

The limitation: the diff checker compares line N with line N and doesn't realign inserted lines. If a repair added a line near the top, everything after it shows as changed. For that case, a diff tool that realigns lines, such as git diff --no-index, gives a cleaner view.

FAQ

Can invalid JSON be fixed automatically?

Often, yes. A repair library such as jsonrepair can add missing quotes and commas, strip trailing commas and comments, and close missing brackets. If it hits a problem it can't solve, it throws a JSONRepairError instead of guessing.

Is it safe to auto-repair JSON from an API or a database?

Only after checking the result. Fixes like swapping single quotes for double quotes don't change the data, but repairing truncated JSON closes the brackets around whatever arrived, so missing records stay missing.

How do I repair JSON from the command line?

Install the jsonrepair CLI with npm install -g jsonrepair, then run jsonrepair broken.json, or pipe a file into it with cat broken.json | jsonrepair. The --output option writes the result to a file.

Should I just parse the file as JSON5 instead?

If the file is a hand-written config with comments and trailing commas, a JSON5 parser reads it as is, since JSON5 is a superset of JSON. That doesn't help with missing commas, missing brackets or truncated data.

Sources