Skip to the content
GigaJSON
All tools
Guides Open GigaJSON

How to fix invalid JSON: the 10 most common errors

· 7 min read

JSON's grammar is small, so it breaks in a small number of ways. If you know the ten below, you can read almost any parse error and know what to look for. Each section shows the broken input, the error that Node.js (the same V8 engine as Chrome) and Python give for it, and the fix.

If you'd rather paste it and see the result, the JSON Repair tool fixes most of these and lists each line it changed. Read on to know when not to trust an automatic fix.

Reading the error message first

Parsers report where they gave up, not where you made the mistake. The two often differ by a line. A missing comma at the end of line 2 shows up as an error at the start of line 3, because that's where the parser sees a token it didn't expect.

So the routine is: go to the line and column in the error, then look one token back. For a quick check without fixing anything, the JSON validator points at the exact position.

1. Trailing commas

The most common one by far, usually from copying a JavaScript object or deleting the last item in a list by hand.

{
  "name": "Ana",
  "tags": ["a", "b",],
}

Node: Unexpected token ']', ..."["a", "b",],..." is not valid JSON Python: Expecting value: line 3 column 21 (char 39)

Fix: delete the comma before every ] and }. In a big file, a regex search for ,\s*[\]}] finds them all.

2. Single quotes or curly quotes

JSON strings and keys need straight double quotes. Single quotes come from Python and JavaScript habits; curly quotes (“name”) come from word processors, chat apps and some note-taking tools that "smarten" quotes as you type.

{'name': 'Ana', 'city': 'Porto'}
{“name”: “Ana”}

Node: Expected property name or '}' in JSON at position 1 (line 1 column 2) Python: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Fix: replace them with ". Watch for apostrophes inside values ('O'Brien'): a blind find-and-replace turns them into broken strings. A repair tool handles that case better than sed does.

3. Unquoted keys

Valid JavaScript, invalid JSON:

{name: "Ana", age: 31}

The error is the same "Expected property name" as above. Fix: {"name": "Ana", "age": 31}.

4. Comments

Config files are where this bites. tsconfig.json and VS Code's settings accept comments because they're read as JSONC, a JSON-with-comments dialect. A strict parser does not.

{
  // retry settings
  "retries": 3, /* seconds */ "timeout": 30
}

Node: Expected property name or '}' in JSON at position 4 (line 2 column 3)

Fix: remove the comments, or parse the file with a JSONC or JSON5 parser if it is meant to have them. If you need to annotate real JSON, a "_comment" key is the usual workaround.

5. Missing commas

Common in hand-edited files and when two snippets get pasted together.

{
  "name": "Ana"
  "age": 31
}

Node: Expected ',' or '}' after property value in JSON at position 20 (line 3 column 3) Python: Expecting ',' delimiter: line 3 column 3 (char 20)

Note that both point at line 3, while the missing comma belongs at the end of line 2. That's the "look one token back" rule.

6. NaN, Infinity and undefined

JSON has no NaN, no Infinity and no undefined. You'll still see them, because Python writes them:

>>> json.dumps({"r": float("nan")})
'{"r": NaN}'

Python reads them back without complaint, so the file works until someone opens it in JavaScript, Go or a database. JavaScript's JSON.stringify goes the other way and silently turns NaN and Infinity into null.

{"ratio": NaN, "max": Infinity, "note": undefined}

Node: Unexpected token 'N', ..."{"ratio": NaN, "max""... is not valid JSON

Fix: decide what the value should mean. Usually that's null. Some repair tools turn NaN into the string "NaN", which parses but may surprise the code reading it. To stop Python producing these, use json.dumps(data, allow_nan=False); it raises an error instead of writing invalid JSON.

7. Python's True, False and None

print(my_dict) or str(my_dict) gives Python syntax, which looks almost like JSON:

{'active': True, 'deleted': False, 'parent': None}

Fix the source: use json.dumps(my_dict), which writes {"active": true, "deleted": false, "parent": null}. If all you have is the log output, a repair tool converts the quotes and constants together.

8. Raw line breaks, tabs and bad backslashes in strings

Inside a JSON string, a line break must be written \n and a tab \t. A real newline in the middle of a string is an error:

{"msg": "line one
line two"}

Node: Bad control character in string literal in JSON at position 17 (line 1 column 18) Python: Invalid control character at: line 1 column 18 (char 17)

Backslashes cause the related problem. Windows paths are the classic case:

{"path": "C:\Users\ana\new"}

Node: Bad escaped character in JSON at position 13 (line 1 column 14) Python: Invalid \escape: line 1 column 13 (char 12)

Fix: double every backslash ("C:\\Users\\ana\\new") or use forward slashes, which Windows accepts too. Be careful with automatic repair here. The parser can't know that \n in \new was meant as a backslash and an "n" rather than a newline, and \U isn't a valid escape at all. In my tests, jsonrepair (the library behind GigaJSON's repair, among others) produced "C:Usersana\new": valid JSON, wrong data. Fix paths by hand, and if you build JSON strings by concatenation anywhere, switch to a real serializer.

9. Truncated JSON

A file cut off by a full disk, a log line limit, a timeout, or an AI model that ran out of output tokens:

{"items": [{"id": 1, "name": "Ana"}, {"id": 2, "na

Node: Unterminated string in JSON at position 50 (line 1 column 51) Python: Unterminated string starting at: line 1 column 48 (char 47)

Fix: get the complete file if you can. If you can't, close the open strings and brackets so the rest is usable. A repair tool does this mechanically; on the example above, jsonrepair returned:

{"items": [{"id": 1, "name": "Ana"}, {"id": 2, "na": null}]}

The last record is incomplete ("na": null is a guess at a cut key). Drop it or mark it rather than treating it as real data.

10. JSON wrapped in an AI answer

Ask ChatGPT, Claude or Gemini for JSON and you often get a sentence, a fenced code block, and another sentence. Models also add trailing commas and // comments more often than you'd like.

Sure! Here is the JSON you asked for:

```json
{
  "name": "Ana",
  "skills": ["sql", "go"],
}
```

Let me know if you need anything else.

Node: Unexpected token 'S', "Sure! Here"... is not valid JSON

Fix: take only what's between the fences, then fix the trailing comma. In code, extract the block with a regex before parsing:

const m = /```[\w-]*\s*\n([\s\S]*?)```/.exec(answer);
const data = JSON.parse(m ? m[1] : answer);

Better still, ask the model's API for structured output (most providers have a JSON mode or schema option) so there is nothing to strip. When you just have a pasted answer, GigaJSON's JSON Repair recognises the code fence, keeps the block, fixes the comma, and shows the change. Some general-purpose repair setups wrap the surrounding sentences into an array with the JSON instead, so check the output's shape.

What automatic repair can't do

Repair works by guessing the most likely intent. It's good at the cases above, and it should refuse when there's no clear answer. A doubled comma is one example:

{"a": 1,, "b": 2}

Was a value deleted, or was the comma typed twice? jsonrepair stops with Object key expected at position 8, and GigaJSON reports it as line 1, column 9 instead of guessing. That's the right behaviour: you fix it by hand.

Two habits make repair safe:

  • Look at the diff. GigaJSON never repairs silently; in the app and the repair tool you choose "Repair", then "See changes" lists the lines before and after.
  • Fix the producer. If the same error keeps coming back, the code writing the file is building JSON by hand or using the wrong function (str() instead of json.dumps, string concatenation instead of JSON.stringify). Repairing the output every time hides the bug.

Quick reference

Error message contains Likely cause
Expected property name or '}' / enclosed in double quotes single quotes, unquoted key, comment, trailing comma before }
Unexpected token ']' / Expecting value before ] trailing comma in an array
Expected ',' or '}' after property value / Expecting ',' delimiter missing comma (look at the line before)
Unexpected token 'N' or 'I' NaN, Infinity
Bad control character / Invalid control character real newline or tab inside a string
Bad escaped character / Invalid \escape single backslash, often a Windows path
Unterminated string / Unexpected end of JSON input / an error at the very last position file cut off (or empty)
Unexpected token 'S', "Sure!..." or similar text around the JSON, such as an AI answer

Once it parses, the JSON formatter indents it so the next problem is easier to spot. In the app, Repair in the Code tab is a single undo step, so you can go back to the broken text if the result isn't what you wanted.

Questions

How do I find where my JSON is broken?

Read the line and column in the parser's error, then look at that spot and the line before it. A missing comma or quote is often reported on the next token, one line after the real mistake.

Why does JSON.parse fail on JSON that Python printed?

print() on a dict writes Python syntax, not JSON: single quotes, True, False and None. Use json.dumps(data) to get real JSON. Python's json.dumps also writes NaN and Infinity unless you pass allow_nan=False, and other parsers reject those.

Can invalid JSON be fixed automatically?

Most of it, yes. Repair tools such as jsonrepair handle quotes, commas, comments, Python constants, cut-off files and code fences. Always review what changed: a repair can only guess intent, and a few cases (doubled commas, Windows paths with single backslashes) need a human.

How do I get valid JSON out of a ChatGPT or Claude answer?

Copy only the fenced code block, not the sentences around it, and fix trailing commas or comments if the model added them. A repair tool that recognises Markdown fences, like GigaJSON's JSON Repair, extracts the block for you.

Does JSON allow comments or trailing commas?

No. Standard JSON (RFC 8259) has neither. JSON5 and JSONC allow both, and some tools such as VS Code settings accept them, but JSON.parse and most APIs do not.

More from the blog