Fixing Broken JSON: Common Errors and How to Repair Them
You paste a JSON response into your editor, and JSON.parse() throws a cryptic error. The payload looks fine at a glance, but somewhere in hundreds of lines a single misplaced character breaks everything. Here is how to find and fix the most common JSON errors quickly.
Why JSON Breaks
JSON has a strict syntax. Unlike JavaScript objects, it requires double quotes around keys, forbids trailing commas, and does not allow comments. Data that is valid JavaScript often fails as JSON. API responses get corrupted in transit, manual edits introduce typos, and copy-pasting from documentation introduces invisible characters.
The Top 8 JSON Errors
1. Single Quotes Instead of Double Quotes
JSON requires double quotes for strings. Single quotes are invalid.
// Broken
{'name': 'Alice', 'age': 30}
// Fixed
{"name": "Alice", "age": 30}
Fix: replace all single-quoted strings with double-quoted strings. Be careful not to replace single quotes inside string values.
2. Trailing Commas
JavaScript allows trailing commas in arrays and objects. JSON does not.
// Broken
{"items": ["a", "b", "c",]}
// Fixed
{"items": ["a", "b", "c"]}
Fix: remove the comma before every closing ] or }.
3. Unquoted Keys
JavaScript object keys do not need quotes if they are valid identifiers. JSON always requires them.
// Broken
{name: "Alice", age: 30}
// Fixed
{"name": "Alice", "age": 30}
4. Missing Commas Between Elements
A missing comma between two key-value pairs or array elements is hard to spot visually.
// Broken
{"name": "Alice" "age": 30}
// Fixed
{"name": "Alice", "age": 30}
The error message typically says "unexpected string" at the position where the comma should be.
5. Unescaped Special Characters in Strings
Newlines, tabs, and backslashes inside strings must be escaped. Raw control characters are invalid.
// Broken (contains a literal newline)
{"message": "Hello
World"}
// Fixed
{"message": "Hello\nWorld"}
Other characters that must be escaped: \", \\, \t, \r, \b, \f, and Unicode escapes \uXXXX.
6. Comments
JSON does not support comments. Neither // nor / / is valid.
// Broken
{
"debug": true, // enable debug mode
"port": 3000
}
// Fixed
{
"debug": true,
"port": 3000
}
If you need comments in configuration files, consider JSON5 or JSONC (JSON with Comments, supported by VS Code's tsconfig.json).
7. Undefined and NaN
JavaScript's undefined and NaN are not valid JSON values. Use null for missing values and a string or special object for non-numeric results.
// Broken
{"value": undefined, "ratio": NaN}
// Fixed
{"value": null, "ratio": null}
8. Mismatched Brackets
An extra or missing {, }, [, or ] corrupts the entire structure. This is especially common in manually edited files.
The best way to find mismatched brackets is to use an editor with bracket matching or a JSON formatter that highlights the error location.
Automated Repair Strategy
A JSON fixer can address most of these issues programmatically:
function fixCommonJsonErrors(input: string): string {
let fixed = input;
// Remove BOM
fixed = fixed.replace(/^\uFEFF/, "");
// Remove single-line comments
fixed = fixed.replace(/\/\/[^\n]*/g, "");
// Remove multi-line comments
fixed = fixed.replace(/\/\*[\s\S]*?\*\//g, "");
// Replace single quotes with double quotes (simple cases)
fixed = fixed.replace(
/(?<=[:,\[\{\s])'/g, '"'
).replace(
/'(?=[,\]\}\s:])/g, '"'
);
// Remove trailing commas before } or ]
fixed = fixed.replace(/,\s*([\]}])/g, "$1");
// Quote unquoted keys
fixed = fixed.replace(
/(\{|,)\s*([a-zA-Z_$][\w$]*)\s*:/g,
'$1"$2":'
);
return fixed;
}
This handles the most frequent issues but cannot fix deeply structural problems like mismatched brackets. For those, a proper parser with error recovery is needed.
Reading JSON.parse Error Messages
When JSON.parse() fails, the error message includes a position:
SyntaxError: Unexpected token ' in JSON at position 42
Position 42 is the character index (zero-based) in the string. Find it by counting characters or using:
try {
JSON.parse(jsonString);
} catch (e) {
const match = e.message.match(/position (\d+)/);
if (match) {
const pos = parseInt(match[1]);
const context = jsonString.substring(
Math.max(0, pos - 20),
pos + 20
);
console.log(`Error near: ...${context}...`);
console.log(`${"~".repeat(20)}^ here`);
}
}
This gives you a 40-character window around the error, making it much easier to spot the problem.
Prevention
- Never hand-edit JSON. Use a JSON editor or generate it programmatically.
- Validate on write. Run
JSON.parse(JSON.stringify(data))as a sanity check before saving. - Use JSON5 for config files where you need comments and trailing commas.
- Set Content-Type headers correctly.
application/jsontells clients to expect strict JSON. - Log raw responses before parsing so you can inspect the exact payload when parsing fails.
Try our JSON Fixer to repair broken JSON automatically — right in your browser, no upload required.