JSON guide · 6 min read
How to Fix Invalid JSON: Common Errors and Examples
Diagnose invalid JSON, understand the parser error, repair common syntax problems and verify the corrected payload before using it.
Start by separating syntax errors from data problems
Invalid JSON means the text does not follow JSON grammar and therefore cannot be parsed as a JSON value. That is different from a document that is valid JSON but contains the wrong fields, wrong business values or the wrong schema. Fix syntax first; only then validate the structure expected by your application.
When a parser reports a position, line or character, preserve the original payload before changing it. Formatting a broken document, copying only part of it or retyping the failing line can move the error and hide the original cause.
- Keep an untouched copy of the failing payload.
- Validate the raw text before trying to pretty-print it.
- Inspect several characters before the reported error, not only the reported character.
- After syntax is fixed, validate the result against any API or JSON Schema contract you use.
1. Remove trailing commas
JSON does not allow a comma after the final property of an object or the final element of an array. JavaScript, configuration formats and hand-edited examples sometimes tolerate trailing commas, which is why this mistake frequently appears when data is copied into JSON.
The parser may point at the closing brace or bracket rather than at the comma itself. Read the error location as the point where parsing became impossible, not necessarily as the exact place where the mistake began.
Invalid:
{
"name": "JSON Hearth",
"active": true,
}
Valid:
{
"name": "JSON Hearth",
"active": true
}2. Use double quotes and escape strings correctly
JSON property names and string values use double quotes. Single-quoted strings, unquoted property names and JavaScript template strings are not JSON syntax even though they may look natural in application code.
A quote inside a JSON string must be escaped. Backslashes also introduce escape sequences, so Windows paths, regular expressions and JSON embedded inside another string are common sources of mistakes.
Invalid:
{'name': 'Ada'}
{"message": "She said "hello""}
Valid:
{"name": "Ada"}
{"message": "She said \"hello\""}3. Check commas, braces and brackets as a group
A missing comma between adjacent properties can make the parser fail on the next property name. Likewise, an extra closing bracket can make an otherwise correct section appear broken. Deeply nested API responses are easier to debug when you reduce the failing document to the smallest object or array that still reproduces the problem.
- Every opening { needs a matching } and every opening [ needs a matching ].
- Object properties and array elements need commas between them, but not after the final item.
- Do not assume the final line is at fault when the parser reports an unexpected end of input; the missing delimiter may be much earlier.
- For large files, isolate a representative branch instead of manually counting thousands of delimiters.
Invalid:
{
"user": {
"id": 42
"active": true
}
}
Valid:
{
"user": {
"id": 42,
"active": true
}
}4. Replace JavaScript-only values
JSON supports strings, numbers, objects, arrays, true, false and null. Values such as undefined, NaN, Infinity, functions, BigInt literals and Date objects are JavaScript concepts and cannot appear directly in JSON text.
If those values are meaningful to your application, choose an explicit JSON representation. Dates are commonly serialized as strings, unavailable values may become null or an omitted field, and very large identifiers are often safer as strings when precision must be preserved across languages.
Invalid:
{"lastSeen": undefined, "score": NaN}
Possible JSON representation:
{"lastSeen": null, "score": null}5. Look for invisible characters and encoding problems
A payload can look correct in an editor and still fail because it contains an unescaped control character, a byte-order mark, a non-standard quote copied from rich text or damaged text encoding. Newlines and tabs are allowed between JSON tokens, but literal control characters inside a quoted string must be escaped.
If a failure occurs at the first character even though the document visibly starts with { or [, inspect the raw bytes or copy the content into a plain-text editor. Files exported by older tools can occasionally include prefixes that a strict parser does not expect.
6. Confirm that an API really returned JSON
Many 'invalid JSON' bugs are not JSON-generation bugs at all. A client expects JSON, but the server returns an HTML login page, reverse-proxy error, plain-text stack trace or empty response. Parsing then fails even though your client code is correct.
Check the HTTP status and Content-Type before calling JSON.parse. During debugging, log a short, redacted prefix of the raw response so you can tell the difference between malformed JSON and a completely different response format.
const response = await fetch(url);
const raw = await response.text();
console.log(response.status, response.headers.get("content-type"));
console.log(raw.slice(0, 200));
const data = JSON.parse(raw);A reliable repair workflow
Use the JSON Syntax Validator on the unchanged payload first. Read the reported location and inspect the surrounding text. If the problem is a common formatting mistake, Fix Broken JSON can create a candidate repair, but treat that output as a suggestion rather than as proof of the intended data.
After repair, run the validator again, format the result for visual inspection and compare important values with the original source. Automatic repair is safest when the intended structure is obvious; it cannot reliably guess a missing value or business meaning.
- Validate the original payload.
- Repair only the syntax that is demonstrably broken.
- Validate the repaired result again.
- Pretty-print and inspect important branches.
- Run schema or application-level validation before production use.
Prevent invalid JSON at the source
Avoid constructing JSON with string concatenation. Let your language's serializer produce JSON from typed values or normal data structures. This removes an entire class of quoting, escaping and delimiter errors.
For APIs, add contract tests that parse representative responses and include malformed or missing-field cases. For configuration, validate files in CI before deployment. The cheapest JSON error to debug is the one rejected before it reaches another service.
// Prefer serialization
const payload = JSON.stringify({ name: "Ada", active: true });
// Avoid hand-built JSON strings
// const payload = '{"name":"' + name + '"}';Primary sources
References and specifications
- RFC 8259 — The JavaScript Object Notation (JSON) Data Interchange Format
The IETF specification for JSON syntax, values, interoperability and parser behavior.
- ECMA-404 — The JSON Data Interchange Syntax
The concise ECMA definition of JSON grammar.
Common questions
Frequently asked questions
Can invalid JSON be repaired automatically?
Many mechanical mistakes can be repaired automatically, including some missing quotes, trailing commas and incomplete delimiters. The repaired output still needs review because a tool cannot infer ambiguous missing values or business intent.
Why is my JavaScript object not valid JSON?
JavaScript object syntax allows features JSON does not, including single quotes, comments, undefined, methods and sometimes unquoted property names. Serialize the object with JSON.stringify instead of copying source-code syntax.
Why does valid-looking JSON fail at position 0?
The response may be empty, HTML, plain text or prefixed by an unexpected byte-order mark. Inspect the raw response, HTTP status and Content-Type before assuming the JSON itself is wrong.
Should I format broken JSON before debugging it?
Not initially. A formatter normally has to parse the document first, and changing the text can move the original error. Validate the raw payload, repair it, then format the valid result.