Guides••10 min read

How to Fix Invalid JSON: Pattern-by-Pattern Repair Guide

The most common broken-JSON patterns and the exact fix for each. Trailing commas, single quotes, JS comments, truncated payloads, smart quotes from Word.

By JSONEditor.net Team

Where broken JSON comes from

Broken JSON almost never comes from a JSON file you wrote from scratch. It comes from these sources, in roughly this order of frequency:

  1. Copy-paste from a JavaScript object literal in someone's blog post.
  2. Copy-paste from API documentation that uses trailing commas for "readability."
  3. Hand-edited config file where someone deleted a line along with its comma.
  4. API response truncated by a proxy timeout.
  5. Paste from Microsoft Word or Google Docs that helpfully replaced your quotes with curly quotes.
  6. JSON wrapped in HTML, with the document's " entities never decoded.
  7. The output of an LLM that started with backticks and a language label.

Each pattern has a deterministic fix. This guide goes through them with the exact regex or rule that resolves the case. If you want the auto-applied version, the repair tool on this site handles the common ones in one click.

Trailing commas

The single most common case. Anything that lets you put a comma after the last array or object item — JavaScript, Python, Ruby, modern C# — will train your fingers to type one. JSON rejects it.

// broken
{
  "items": [1, 2, 3,],
  "ok": true,
}

// fix
{
  "items": [1, 2, 3],
  "ok": true
}

The regex that fixes 99% of trailing-comma cases is:

text.replace(/,(\s*[}\]])/g, '$1')

The 1% it misses: a literal comma inside a string immediately followed by whitespace and a brace. For example, {"sentence": "hello, "} — but the closing quote protects it, so the regex actually does the right thing. It only fails on pathological constructed strings, not real-world data.

Single quotes everywhere

JavaScript treats single and double quotes as interchangeable. JSON requires double quotes. Pasted JS object literals or Python dicts will be full of single quotes.

// broken
{ 'name': 'Ada', 'born': 1815 }

// fix
{ "name": "Ada", "born": 1815 }

The naive replace — text.replace(/'/g, '"') — works on simple cases but mangles strings that legitimately contain apostrophes. A safer pass scans for string-like sequences preceded by a structural character (:, ,, [, {):

text.replace(
  /([:,\[{(]?\s*)'((?:[^'\\]|\\.)*)'/g,
  (_m, prefix, body) => {
    const escaped = body.replace(/\\'/g, "'").replace(/"/g, '\\"');
    return `${prefix}"${escaped}"`;
  }
)

If your input has nested apostrophes inside strings ("it's a test"), normalise by hand or let the repair tool handle it — the auto-repair runs this exact transform and re-validates afterward.

Comments left in by accident

JSON has no comments. Period. JSONC (used by VS Code's settings) and JSON5 do, but standard parsers will reject them.

// broken
{
  // database connection
  "host": "localhost",
  "port": 5432  /* default postgres port */
}

// fix
{
  "host": "localhost",
  "port": 5432
}

Two regex passes strip both styles:

text
  .replace(/\/\*[\s\S]*?\*\//g, '')  // block comments
  .replace(/\/\/[^\n\r]*/g, '')        // line comments

Edge case: a string value that happens to contain // — like a URL. The naive regex will eat everything from the slashes to the next newline. If your data has URLs, use a real tokenizer or accept that you cannot regex-fix this case. jsonc-parser from VS Code's repo is the reference implementation if you need to handle JSONC properly.

Unquoted keys

JavaScript object literals allow keys without quotes when the key is a valid identifier. JSON always requires double quotes.

// broken
{ name: "Ada", age: 36 }

// fix
{ "name": "Ada", "age": 36 }

The regex that adds quotes around bare identifier keys:

text.replace(
  /([{,]\s*)([A-Za-z_$][A-Za-z0-9_$]*)(\s*:)/g,
  '$1"$2"$3'
)

This handles keys made of letters, digits, dollar signs, and underscores — covering identifier-style keys from JavaScript, Java, and most language conventions. Keys with hyphens or dots need a different rule and are unlikely to be unquoted in the first place.

Truncated payloads

An API response cut off by a proxy timeout or a stream that disconnected mid-write. The document is valid up to a point and then just stops.

// example: an array of users, cut off
[
  { "id": 1, "name": "Ada" },
  { "id": 2, "name": "Bob" },
  { "id": 3, "name": "Cha

There is no regex for this. You have two choices.

If you control the producer: fix it there. A truncated stream is a transport bug, not a JSON bug. Use a content-length header, retry on incomplete responses, or stream NDJSON (newline-delimited JSON) so each line is independently valid.

If you only have the broken bytes: parse incrementally. Walk back from the truncation point until the document is valid. For an array, that means finding the last complete element and closing the array. The jsonrepair library on npm implements this — it adds missing brackets and quotes by walking the token stream. It is not magic; some truncations are unrecoverable. But for "lost the last array item" it usually returns something usable.

Mismatched braces and quotes

Hand-edited JSON often ends up with one too many or one too few of {, }, [, or ]. The parser reports a position, but the actual error is usually earlier — you typed } when you meant ], and the parser only notices several lines later.

The fastest debugging move: paste the JSON into the validator, note the reported position, and walk backward from there counting opening and closing brackets. Most editors highlight the matching pair when you put the cursor on a bracket — VS Code does this by default. Move through each opening bracket and confirm its match is what you intended.

For unmatched quotes, the parser usually fails partway through a string. Look for the most recent " before the error position — that is the open quote that never closed.

Encoding issues (BOM, smart quotes)

Two encoding traps catch people who paste JSON from a non-developer source.

Byte Order Mark (BOM)

Files saved by Windows Notepad and some Excel exports begin with three bytes (0xEF 0xBB 0xBF) that mark the file as UTF-8. JSON.parse in Node and the browser rejects these because the first character is supposed to be { or [, not an invisible byte. Strip it:

const clean = text.replace(/^\uFEFF/, '');
JSON.parse(clean);

Smart quotes

Word, Google Docs, Slack, and macOS text inputs auto-replace straight quotes with typographic ones: " becomes " and ". To human eyes they look identical. To JSON.parse they are completely different characters.

const clean = text
  .replace(/[\u201C\u201D]/g, '"')  // curly double quotes
  .replace(/[\u2018\u2019]/g, "'"); // curly single quotes

If you are accepting JSON pasted from a web form, run this normalisation on the input before parsing. It saves hours of "but it looks fine in my editor" debugging.

Auto-repair vs hand-fixing

Auto-repair is fine for transient JSON: an API response you need to inspect once, a config someone sent over Slack, a payload pasted from a Word document. Run it through the repair tool, copy the result, move on.

Hand-fix is the right move for source-controlled files. The auto-repair makes guesses — which single quote was a string delimiter, where a missing comma belongs. Each guess is reasonable in isolation but commits drift over time. Fixing it by hand once, with the validator pointing you at the line, takes a minute and produces JSON that survives the next round-trip through your build pipeline unchanged.

The one case where auto-repair beats hand-fix: you have hundreds of broken files. Then a programmatic pass with the rules from this post, followed by a validator check on the output, beats clicking through them. Just keep the originals — if the auto-repair guessed wrong, you want to be able to diff back to the source.

JSONCSVConvertersData