Developer workflow
How to Validate and Troubleshoot JSON Errors
Diagnose common JSON syntax errors, locate parser messages, validate safely in JavaScript, and troubleshoot API responses with practical examples.
Introduction
JSON syntax errors often surface while integrating an API, editing configuration, inspecting a request or response, or transforming data between systems. The parser message can be terse, and the mistake may be just before the reported position. This guide shows how to recognize valid JSON, fix common syntax problems, and inspect the full response when an API call does not return the JSON you expected.
1. What Counts as Valid JSON?
JSON (JavaScript Object Notation) is a text format for exchanging data. A JSON document contains one value: an object, array, string, number, boolean, or null. Objects contain quoted string keys and values separated by commas; arrays contain values separated by commas. Strings and object keys use double quotes.
This is a valid JSON object containing each common value type:
{
"name": "Mina",
"items": ["book", "pen"],
"count": 2,
"active": true,
"note": null
}A JSON text may be a scalar value as well as an object or array. Whitespace around values is allowed. Comments, undefined, functions, and special numeric values such as NaN and Infinity are not JSON values.
2. Common JSON Errors and Fixes
Single quotes
JSON strings must use double quotes. A single quote is not an alternate delimiter:
{'name': 'Mina'} // invalid JSON{"name": "Mina"}Unquoted object keys
Every object key must be a JSON string, even when it looks like a simple identifier. Quote it with double quotes:
{name: "Mina"} // invalid JSON{"name": "Mina"}Trailing commas
The last item in an object or array must not be followed by a comma. Remove the comma before the closing brace or bracket:
{
"name": "Mina",
} // invalid JSON{
"name": "Mina"
}Missing commas
Separate neighboring properties and array items with commas. In this example, the parser reaches the next key while still expecting a comma after the string value:
{
"name": "Mina"
"active": true
} // missing comma{
"name": "Mina",
"active": true
}Invalid strings and escaping
A double quote inside a JSON string must be escaped. A backslash begins an escape sequence; common valid escapes represent a quote, backslash, line break, tab, or Unicode code point. A bare line break or an unknown escape makes the string invalid.
{
"quote": "She said \"hello\"",
"path": "C:\\work\\file.json",
"lineBreak": "first\nsecond"
}Invalid numbers
JSON numbers use decimal notation with an optional minus sign, fractional part, and exponent. A fraction needs digits after the decimal point; an exponent needs digits after its optional sign. Leading zeros are not allowed on ordinary integer parts (except the value 0), and plus-prefixed numbers, NaN, and Infinity are invalid.
01 // invalid leading zero
1. // missing fractional digits
+2 // leading plus is invalid
1e // missing exponent digits0
-12
3.5
6.02e23
-4E-23. JSON and JavaScript Objects Are Different
JavaScript object literals have syntax features JSON does not. For example, this is valid JavaScript:
const user = {
name: 'Mina',
};It is not JSON: the key is unquoted, the string uses single quotes, and there is a trailing comma. JSON is a data interchange format with a deliberately narrower grammar; it does not include JavaScript variables, comments, expressions, or executable code. If an API or configuration file expects JSON, send or save JSON text rather than a JavaScript object literal.
4. Find the Error Position
When a parser reports a line and column, start at that location and inspect the surrounding characters. Also check the previous token: a missing comma, quote, or closing delimiter often makes the parser complain where it next becomes impossible to continue, rather than exactly where the original mistake began. In nested data, trace the open braces and brackets back to their matching closing characters.
Line and column conventions vary between parsers, and some browser error messages do not expose a reliable position. Treat a reported location as a useful starting point, not proof that the character under the cursor is the root cause. Paste the input into the JSON Formatter & Validator to validate it and inspect available line and column feedback. The tool formats valid JSON locally and does not repair malformed syntax automatically.
5. Validate JSON in JavaScript or TypeScript
Use JSON.parse() to parse JSON text. Catch SyntaxError so invalid input becomes an expected validation result instead of an unhandled exception:
function parseJson(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (error) {
if (error instanceof SyntaxError) {
return { ok: false, message: error.message };
}
throw error;
}
}Parsing confirms that the text follows JSON syntax. It does not check that the resulting value has the fields or types your application requires. For that, validate the parsed value against an application-specific schema. For example, you can generate a starting TypeScript type with JSON to TypeScript or a runtime validator with JSON to Zod. Review generated definitions against your real API contract.
Do not use eval() to parse JSON. It executes JavaScript, so input that looks like data could instead run code. JSON.parse() accepts JSON syntax and does not evaluate JavaScript expressions.
6. Format and Minify JSON Safely
Pretty formatting adds indentation and line breaks to make a valid JSON value easier to inspect. Minification removes insignificant whitespace while preserving the parsed data. Neither operation fixes invalid syntax or changes a value into a different data shape.
A safe workflow is to parse first, then serialize the parsed value with the formatting you need. In JavaScript, JSON.stringify(value, null, 2) produces two-space indentation; JSON.stringify(value) produces compact output. Use the JSON Formatter & Validator to format or minify a pasted value in your browser.
7. Troubleshoot an API Response That Should Be JSON
A parse error does not always mean the server returned almost-correct JSON. First confirm that you actually received the expected response:
- Check the HTTP status. A failed request may return an error body with a different format.
- Inspect the response body as text before parsing. An HTML login page, proxy error, or framework error document is not JSON.
- Check the Content-Type header. It should identify JSON (commonly application/json or a compatible +json media type) when the endpoint returns JSON.
- Confirm the request reached the expected server, environment, and route. A redirect, gateway, or proxy can produce a different body.
- Check for truncation: compare the body ending and transfer/network errors with the server-side response. A cut-off string or unclosed object often indicates an incomplete body.
- Check character encoding and escaping. JSON exchanged on the web is expected to use UTF-8; malformed byte decoding or double-escaped content can produce unexpected characters.
- Compare the raw body with the server output. If the server emits invalid JSON, fix serialization at the source instead of patching the client response.
Avoid logging full production payloads when investigating. Prefer a redacted sample, request ID, status, headers, and a short safe excerpt so debugging does not expose credentials or personal data.
8. JSON Validation Checklist
- Use double quotes for strings and object keys.
- Separate properties and array items with commas; remove a comma after the last item.
- Escape quotes, backslashes, and control characters inside strings.
- Use only JSON values: object, array, string, number, true, false, and null.
- Check that braces and brackets are balanced and in the correct order.
- When parsing an API response, inspect its status, headers, and raw body before assuming the body is JSON.
- Use JSON.parse() and handle SyntaxError; validate the parsed shape separately when needed.
Frequently Asked Questions
Why is my JSON invalid?
Common causes are single quotes, unquoted keys, missing or trailing commas, invalid escapes, and numbers outside JSON syntax. Check the reported position and the token immediately before it.
Can JSON use single quotes?
No. JSON strings and object keys use double quotes.
Can JSON have trailing commas?
No. The last property or array item must not be followed by a comma.
Is JavaScript object syntax the same as JSON?
No. JavaScript object literals allow syntax that JSON does not, such as unquoted keys, single-quoted strings, trailing commas, and expressions.
How do I validate JSON?
Use JSON.parse() in JavaScript or a JSON validator. Catch parse errors, then validate the parsed value against your application schema if you need to check its shape.
How do I find the JSON error line?
Use a parser that reports a line and column when available. Parser positions can vary and may identify where parsing failed rather than where the original typo began, so inspect nearby tokens too.
Can JSON contain comments?
No. Standard JSON has no comment syntax. Remove comments before parsing or use a different, explicitly supported configuration format.