Fix Invalid JSON: Every Error Type and How to Fix It
Broken JSON? Paste it in and get it fixed in under 1 second — free, no signup. Covers SyntaxError, JSONDecodeError, trailing commas, bad quotes, Python literals, and 16 more.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →Invalid JSON errors are among the most frustrating in software development because the error message rarely tells you where the problem actually is. A SyntaxError: Unexpected token in JavaScript, JSONDecodeError in Python, or a blank failure in Postman all mean the same thing: the string you're trying to parse isn't valid JSON. This guide covers every common cause, how to locate the problem, and how to fix it.
Why JSON Is So Strict
JSON follows RFC 8259, which has zero tolerance for deviations. Valid JSON must use:
- Double quotes for strings (not single quotes)
true,false,null(lowercase only)- No trailing commas
- No comments
- No
undefined,NaN, orInfinityvalues
Every parser — browser, Python, Node.js, Java — enforces the same spec. If you learned JSON from JavaScript source code or AI output, you've almost certainly encountered patterns that look valid but aren't.
The Most Common Causes of Invalid JSON
1. Trailing Commas
The single most common JSON error. Both objects and arrays forbid trailing commas.
// INVALID
{
"name": "Alice",
"age": 30,
}
// VALID
{
"name": "Alice",
"age": 30
}
This error is especially common in JSON generated by AI tools, which frequently mirror JavaScript coding habits where trailing commas are allowed (and even encouraged by linters).
2. Single Quotes Instead of Double Quotes
JSON requires double quotes. Single-quoted strings will fail in every parser.
// INVALID
{'name': 'Alice', 'age': 30}
// VALID
{"name": "Alice", "age": 30}
If your JSON came from a Python script or a shell command, single quotes are the most likely culprit.
3. Unquoted Keys
JavaScript objects allow unquoted keys. JSON does not.
// INVALID
{name: "Alice", age: 30}
// VALID
{"name": "Alice", "age": 30}
AI language models are trained on JavaScript source code and frequently output unquoted keys, especially for simple objects.
4. Python Boolean and Null Values
Python uses True, False, and None. JSON requires true, false, and null.
# INVALID JSON (Python syntax)
{"active": True, "data": None, "error": False}
# VALID JSON
{"active": true, "data": null, "error": false}
If you're using json.dumps() in Python, it handles this automatically. The problem appears when you hardcode values or paste Python dict output directly.
5. JavaScript Comments
JSON allows no comments. Neither // line comments nor / / block comments are valid.
// INVALID
{
"name": "Alice", // primary user
"age": 30 / verified /
}
// VALID
{
"name": "Alice",
"age": 30
}
6. Markdown Code Fences
When you ask an AI model to return JSON, it often wraps the output in markdown code fences:
{"name": "Alice", "age": 30}
The backticks and json language tag are not part of the JSON. Any parser will reject them immediately.
7. NaN, Infinity, and undefined
These are JavaScript values. They are not valid JSON.
// INVALID
{"score": NaN, "ratio": Infinity, "data": undefined}
// VALID (substitute with null or a sentinel value)
{"score": null, "ratio": null, "data": null}
8. Truncated JSON from Streaming APIs
When an LLM hits its token limit mid-response, the JSON is cut off, leaving unclosed brackets, arrays, and strings:
// INVALID (truncated)
{"users": [{"name": "Alice"}, {"name": "Bob"
// What it should be
{"users": [{"name": "Alice"}, {"name": "Bob"}]}
This is very common with OpenAI JSON mode, Claude, and Gemini when you don't set max_tokens high enough or when the response is unexpectedly long.
9. BOM Characters and Invisible Unicode
Some text editors and file readers prepend a UTF-8 BOM (\xEF\xBB\xBF) to files. This character is invisible in most editors but immediately breaks JSON parsers. Zero-width spaces and other invisible Unicode characters cause the same issue.
10. Duplicate Keys
Technically parseable in most implementations, but undefined behavior in the spec. Some strict parsers reject it.
// Undefined behavior
{"name": "Alice", "name": "Bob"}
How to Find Where the JSON Is Invalid
The error message usually includes a position number, but it's often off by one or points to the character after the problem.
In JavaScript:try {
JSON.parse(input);
} catch (e) {
console.log(e.message); // "Unexpected token , in JSON at position 42"
}
Position 42 means the parser failed at character 42, but the real problem is often a few characters earlier (like a missing closing quote that causes the next comma to be unexpected).
In Python:import json
try:
json.loads(input)
except json.JSONDecodeError as e:
print(f"Line {e.lineno}, Column {e.colno}: {e.msg}")
Python's error is more helpful — it gives line and column numbers.
Visual strategy: Find the position from the error, then scan backwards for:- An unclosed string
- A missing comma
- A stray character
- A comment or code fence
How to Fix Invalid JSON Automatically
For simple cases, you can fix JSON manually. For complex or AI-generated JSON, use a repair tool that understands all the patterns above.
The JSON Repair Tool at AI JSONMedic is built specifically for this. It runs a 16-stage repair pipeline that handles every error type in this guide: strips markdown fences, converts Python booleans, removes trailing commas, quotes unquoted keys, closes truncated structures, removes comments, and more. Paste your broken JSON and get the fixed version plus a plain-English explanation of every change made.
Fixing JSON in Code
If you're getting invalid JSON from an API programmatically and need to repair it at runtime:
JavaScript — minimal repair:function tryFix(str) {
// Strip markdown fences
str = str.replace(/^``(?:json)?\n?/i, '').replace(/\n?``$/,'');
// Remove trailing commas
str = str.replace(/,\s*([}\]])/g, '$1');
return JSON.parse(str);
}
Python — using the tool's API:import requests
response = requests.post(
'https://aijsonmedic.com/api/repair',
data=broken_json,
headers={'Content-Type': 'application/json'}
)
fixed = response.json()
For production use, the API endpoint returns the repaired JSON along with a detailed report of every fix applied.
Validating JSON Before Parsing
If you need to validate JSON without repairing it:
JavaScript:function isValidJson(str) {
try { JSON.parse(str); return true; }
catch { return false; }
}
Python:def is_valid_json(s):
try:
json.loads(s)
return True
except json.JSONDecodeError:
return False
Use the JSON Validator tool to check validity interactively before integrating into your code.
Quick Reference: Invalid JSON Fix Table
| Error type | Example | Fix |
|---|---|---|
| Trailing comma | {"a":1,} | Remove last comma |
| Single quotes | {'a':'b'} | Replace with double quotes |
| Unquoted keys | {a: 1} | Quote all keys |
| Python booleans | True/False/None | Replace with true/false/null |
| JS comments | // comment | Remove all comments |
| Markdown fences | `json ... ` | Strip fences |
| Truncated JSON | {"a": [1, 2 | Close open structures |
| NaN/Infinity | {"x": NaN} | Replace with null |
| BOM character | \xEF\xBB\xBF{...} | Strip BOM |
Summary
Invalid JSON almost always falls into one of ten patterns: trailing commas, single quotes, unquoted keys, Python syntax, comments, markdown wrappers, invalid values, truncation, invisible characters, or duplicate keys. Most of these come directly from AI-generated output or from developers copying JavaScript patterns into JSON contexts.
For one-off fixes, use the free JSON repair tool to paste your broken JSON and get it repaired instantly with an explanation of exactly what was wrong. If you need to repair, validate, format, and diff JSON all in one workspace, the JSON Studio combines all tools with instant switching between modes. For automated repair in production code, use the API endpoint. If you're processing sensitive data, all repair happens client-side — see the 2026 JSON tool privacy guide for a full breakdown of which tools are safe to trust.
FAQ
What is the most common cause of invalid JSON?
Trailing commas are the single most common cause — they're valid JavaScript but not valid JSON. AI models produce them frequently because they're trained on JavaScript code. The second most common is unquoted keys (also valid in JavaScript but not JSON). Third is single-quoted strings.
How do I fix invalid JSON from an AI model automatically?
Use a JSON repair library. In Python: pip install json-repair, then from json_repair import repair_json; fixed = repair_json(broken). In JavaScript/Node.js: npm install jsonrepair, then import { jsonrepair } from 'jsonrepair'; const fixed = jsonrepair(broken). Or use the JSON Repair API for a language-agnostic POST endpoint.
Does JSON allow comments?
No. Standard JSON does not support comments — not //, not / /, not #. If you need a JSON-like format that allows comments, use JSONC (JSON with Comments) or JSON5. Most JSON parsers will throw a parse error on any comment. Use a repair tool to strip comments before passing to JSON.parse().
What is the difference between JSON and JavaScript object literal syntax?
JSON is a strict subset of text that allows only: double-quoted strings, numbers, booleans (true/false), null, arrays, and objects. JavaScript object literals additionally allow: single-quoted strings, unquoted keys, trailing commas, comments, undefined, NaN, Infinity, and Date objects. This is why AI-generated "JSON" is often actually a JavaScript object literal that won't parse with a JSON parser.
Can I fix truncated JSON from a streaming LLM response?
Yes — truncation produces an unclosed structure (missing }, ], or "). A JSON repair tool can close the open brackets in the correct order and recover whatever data was generated before the cutoff. The only data lost is whatever the model hadn't written yet when the stream stopped.
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles