JSON · 11 min read
How to Fix Invalid JSON: Common Errors and Working Examples
By StringTo Editorial Team · Updated
To fix invalid JSON efficiently, you need to identify the first point where the document stops following JSON grammar. Most JSON parse errors come from a small group of problems: incorrect quotes, missing or trailing commas, unescaped characters, unbalanced braces or brackets, comments, and JavaScript values that JSON does not support. Parser messages such as “Unexpected token in JSON” or “Unexpected end of JSON input” identify where parsing failed, although the actual mistake may appear immediately before that position. This guide provides a repeatable debugging process, working before-and-after examples, and validation practices for repairing JSON without accidentally changing its data.
Start with the first JSON parse error
A JSON parser normally stops at the first character that cannot legally continue the document. Begin with that first reported line, column, or character offset instead of trying to repair every visible problem at once. Later errors may be side effects of the first broken delimiter, so fixing issues in source order produces clearer feedback.
Inspect the reported character and the token immediately before it. If a parser highlights a property name, the real problem may be a missing comma after the previous value. If it reports the end of the input, an object, array, or string may have been left open earlier. Format valid portions of the document to make nesting easier to see, but do not assume a formatter can parse already-invalid input.
Preserve a copy of the original before making changes. For production data, compare the repaired result with the expected schema or producing system. A syntactically valid edit can still be wrong if it deletes an array item, changes a number into a string, or moves a property into a different nested object.
try {
const value = JSON.parse(input);
console.log("Valid JSON", value);
} catch (error) {
console.error("JSON parse error:", error.message);
}- Fix the earliest reported error before investigating later ones.
- Check the token immediately before the highlighted position.
- Keep an unchanged copy of important source data.
- Validate meaning and structure after repairing syntax.
Replace single quotes and quote every property name
Standard JSON requires double quotes around property names and string values. Single quotes are valid in JavaScript string literals but not in JSON. An object copied from application source code may therefore look correct while producing an Unexpected token error as soon as a strict JSON parser encounters the first single quote or unquoted key.
Do not repair this by globally replacing every single quote with a double quote. Apostrophes can be legitimate characters inside text, and a blind replacement may corrupt values. Update structural quotes carefully or serialize the original JavaScript value with a trusted JSON serializer when you control the source.
Double quotes inside a JSON string must be escaped with a backslash. Backslashes themselves may also require escaping, especially in Windows paths and regular expressions. A validator helps distinguish a closing quote from a quote that was intended to remain part of the string.
Invalid:
{'name': 'Ada', role: "engineer"}
Valid:
{
"name": "Ada",
"role": "engineer",
"message": "She said \"hello\"."
}- Use double quotes for every JSON key and string.
- Escape embedded double quotes as backslash-quote.
- Avoid global search-and-replace on unfamiliar data.
- Use JSON.stringify when converting a JavaScript value you control.
Fix missing commas and trailing commas
Commas separate properties in an object and items in an array. A missing comma often causes a parser to report an unexpected string, number, brace, or bracket at the beginning of the next item. Add the separator after the preceding complete value, not at the position where the next token happens to be highlighted.
JSON does not allow a comma after the final property or array item. JavaScript permits trailing commas in many contexts, which makes this mistake common when developers paste an object literal into an API client or configuration file. Remove the comma immediately before a closing brace or bracket.
Never remove all commas in response to an error. First identify whether the current container is an object or array, locate its sibling entries, and check that exactly one comma appears between them. Commas inside quoted text are ordinary characters and should remain untouched.
Invalid missing comma:
{"name": "Ada" "active": true}
Invalid trailing comma:
{"name": "Ada", "active": true,}
Valid:
{"name": "Ada", "active": true}- Place one comma between sibling object properties.
- Place one comma between sibling array items.
- Remove commas directly before closing braces or brackets.
- Do not modify commas contained inside strings.
Balance braces, brackets, and nested structures
Objects open with a brace and close with a brace, while arrays open with a bracket and close with a bracket. An Unexpected end of JSON input message commonly means one of these containers—or a quoted string—was never closed. The missing character may be far above the end of a large minified payload.
Indent the document according to its intended hierarchy and inspect one nesting level at a time. Every property in an object needs a key and a value. Every item in an array needs to be a complete JSON value. When an array contains objects, the object must close before the comma that begins the next array item.
Editor bracket matching is useful, but it cannot always infer the intended structure of malformed input. Compare the document with its schema, API documentation, or a known-good sample. Adding a closing brace at the end may satisfy the parser while placing data in the wrong parent container.
Invalid:
{
"users": [
{"id": 1, "name": "Ada"},
{"id": 2, "name": "Linus"}
}
Valid:
{
"users": [
{"id": 1, "name": "Ada"},
{"id": 2, "name": "Linus"}
]
}- Match every opening brace with a closing brace.
- Match every opening bracket with a closing bracket.
- Close nested values in reverse order of opening them.
- Compare repaired nesting with the expected data schema.
Remove comments and unsupported JavaScript values
Standard JSON does not support line comments or block comments. Remove comments before parsing, but be careful with URLs and text containing slash characters. A regular expression that strips comment-like sequences can damage valid string values. When possible, remove comments at the source or use a parser designed for the documented nonstandard format before serializing clean JSON.
JSON also excludes undefined, NaN, Infinity, functions, symbols, regular-expression literals, hexadecimal literals, and expressions. Valid primitive values are strings, JSON numbers, true, false, and null. Replace unsupported values according to their meaning rather than mechanically changing every occurrence to null.
Numbers cannot begin with a plus sign, use leading decimal points, or end with a decimal point. Leading zeros are not allowed except for the number zero itself. Extremely large integers may parse but lose precision in languages that represent all JSON numbers with floating-point values, so identifiers and exact large integers may need a documented string representation.
Invalid:
{
// Retry configuration
"attempts": 03,
"timeout": undefined,
"ratio": NaN
}
Valid:
{
"attempts": 3,
"timeout": null,
"ratio": null
}- Remove comments without altering comment-like text inside strings.
- Replace undefined and non-finite numbers based on application meaning.
- Use decimal JSON number syntax without leading zeros.
- Represent exact large identifiers as strings when required by the contract.
Repair invalid escapes and hidden characters
A backslash begins an escape sequence inside a JSON string. Supported short escapes include escaped quotation marks, backslashes, forward slashes, and control-character codes such as newline and tab. Unicode escapes use exactly four hexadecimal digits after a lowercase u. An unsupported sequence such as backslash followed by q makes the string invalid.
Literal control characters cannot appear inside JSON strings. A copied newline must be represented as backslash-n rather than inserted directly between the opening and closing quotes. Tabs and carriage returns have the same requirement. Text editors that display control characters can help locate invisible input that a parser reports only as an invalid character.
Byte-order marks, nonbreaking spaces, and typographic quotation marks may enter JSON through documents, messaging tools, or spreadsheets. Curly quotes are not structural double quotes. Remove an unexpected byte-order mark at the beginning, replace typographic delimiters with normal ASCII quotes, and preserve legitimate Unicode characters inside properly quoted strings.
Invalid:
{"path": "C:\new\tools", "note": "first line
second line"}
Valid:
{"path": "C:\\new\\tools", "note": "first line\nsecond line"}- Escape backslashes that are part of the actual string value.
- Represent newlines and tabs with valid JSON escapes.
- Replace curly structural quotes with ordinary double quotes.
- Inspect invisible characters when the displayed JSON looks correct.
Validate, format, and test the corrected JSON
After each repair, run the document through a strict JSON validator. Continue until it parses without syntax errors, then format it with consistent indentation. Pretty printing makes arrays, object boundaries, and accidental nesting changes visible, but formatting is not a substitute for validation because a formatter also needs valid input.
Next, validate the parsed data against its expected schema or application contract. Confirm required properties, types, allowed values, array item structures, and unknown-property behavior. Duplicate keys deserve special attention: parsers may silently keep one value, and standard syntax validation alone may not warn you about the semantic ambiguity.
For sensitive payloads, use tools that process locally in the browser and avoid sharing data through URLs. Remove credentials before using examples in bug reports. StringTo's JSON Validator identifies syntax failures, while JSON Formatter and JSON Pretty Print help review the corrected structure after parsing succeeds.
Repair checklist:
1. Save the original input.
2. Fix the first parser error.
3. Repeat strict validation.
4. Pretty-print the valid result.
5. Check the application schema.
6. Compare values with the original intent.
7. Test before production use.- Require strict parsing before formatting.
- Check schema validity after syntax validity.
- Review duplicate keys and changed data types.
- Keep private JSON local and remove secrets from examples.
Frequently asked questions
How do I fix an Unexpected token in JSON error?
Open the reported line, column, or character offset and inspect that token plus the value immediately before it. Common causes include single quotes, unquoted keys, missing commas, trailing commas, comments, unsupported values, and unescaped characters. Fix the earliest error and validate again.
What causes Unexpected end of JSON input?
The input may be empty, truncated, or missing a closing quote, brace, or bracket. Confirm that the complete response or file was received, then inspect open strings and nested containers from the beginning of the document.
Are trailing commas allowed in JSON?
No. Standard JSON requires commas between object properties and array items but rejects a comma after the final entry. Remove any comma immediately before a closing brace or bracket.
Can JSON contain comments?
Standard JSON does not support comments. Some tools accept extended formats, but those documents are not portable JSON. Keep explanations in documentation or use a format explicitly designed to support comments.
Why is valid JSON still rejected by an API?
Syntax validity only means the document can be parsed. The API may require specific properties, data types, values, authentication, content headers, or size limits. Validate the parsed document against the API's schema and contract.
Can a JSON formatter automatically repair invalid JSON?
A strict formatter cannot safely format content it cannot parse. Automatic repair may guess the wrong structure or value. Use the parser position to repair the source deliberately, validate it, and then apply formatting.