Why Is My JSON Invalid? Every Error Explained and Fixed (2026)
You have JSON that should work but does not. The parser throws an error, your API call fails, your config file breaks the application on startup, or your code editor shows red underlines everywhere. JSON is unforgiving — one wrong character invalidates the entire document, and the error messages are often cryptic. This guide covers every cause of invalid JSON, with the exact fix for each one.
How to Find a JSON Error Instantly
Before anything else: paste your JSON into ToolPry's JSON Formatter. It validates in real time as you type and highlights the exact character and line where the error is. This single step solves most JSON problems in under 10 seconds. The formatter shows the error location in the source text, which is far more useful than the character position number most parsers report.
If you cannot share your JSON with an online tool (it contains sensitive production data), use the command line instead: python3 -m json.tool yourfile.json — it validates and prints the exact line and column of any error, with no data leaving your machine.
The 9 Most Common Reasons JSON Is Invalid
1. Trailing comma after the last item
This is the single most common JSON error. JavaScript allows trailing commas in objects and arrays. JSON does not. When you copy a JavaScript object literal into a JSON context, the trailing comma breaks parsing.
// INVALID
{
"name": "Maria",
"role": "admin",
}
// VALID
{
"name": "Maria",
"role": "admin"
}
The error message points to the closing brace, not the comma. Always check the line immediately before the closing bracket when the error points at } or ].
2. Single quotes instead of double quotes
JSON requires double quotes for all strings — both keys and values. Single quotes are valid JavaScript but invalid JSON. This trips up developers copying from JavaScript, Python dictionaries, or any language that uses single-quoted strings.
// INVALID
{'name': 'Maria', 'role': 'admin'}
// VALID
{"name": "Maria", "role": "admin"}
3. Unquoted keys
JavaScript object literals allow unquoted keys if they are valid identifiers. JSON requires all keys to be double-quoted strings — no exceptions.
// INVALID (valid JavaScript, invalid JSON)
{name: "Maria", role: "admin"}
// VALID
{"name": "Maria", "role": "admin"}
4. Comments
JSON does not support comments of any kind. Not //, not /* */, not #. If you need comments in configuration files, use JSONC (JSON with Comments, supported by VS Code), YAML, or TOML instead. Strip all comments before parsing standard JSON.
// INVALID
{
// Server configuration
"host": "localhost",
"port": 5432
}
// VALID
{
"host": "localhost",
"port": 5432
}
5. Undefined, NaN, Infinity values
JSON has six types: string, number, boolean, null, object, array. JavaScript's undefined, NaN, and Infinity are not valid JSON values. If you serialise JavaScript objects that contain these, the result is invalid JSON.
// INVALID
{"score": NaN, "limit": Infinity, "data": undefined}
// VALID — convert to null or omit
{"score": null, "limit": null}
6. Unescaped special characters in strings
Inside a JSON string, double quotes and backslashes must be escaped with a backslash. Newlines must be written as \n, not actual line breaks. Windows file paths are particularly problematic because of their backslashes.
// INVALID
{"path": "C:\Users\Maria\Documents", "message": "She said "hello""}
// VALID
{"path": "C:/Users/Maria/Documents", "message": "She said \"hello\""}
The safest fix: use your language's JSON serialiser (JSON.stringify() in JavaScript, json.dumps() in Python) rather than constructing JSON strings by concatenation. The serialiser handles all escaping automatically.
7. Missing comma between properties
Every property in a JSON object must be separated by a comma. Every element in a JSON array must be separated by a comma. Forgetting a comma — especially when adding a new property to an existing object — is a common mistake.
// INVALID
{
"name": "Maria"
"role": "admin"
}
// VALID
{
"name": "Maria",
"role": "admin"
}
8. Mismatched brackets or braces
Every opening brace { needs a closing brace }. Every opening bracket [ needs a closing bracket ]. In deeply nested JSON, it is easy to lose track. The formatter's tree view helps immediately — it shows the nesting depth and makes mismatches obvious.
// INVALID — missing closing bracket
{
"users": [
{"name": "Maria"},
{"name": "Carlos"}
}
// VALID
{
"users": [
{"name": "Maria"},
{"name": "Carlos"}
]
}
9. Numbers formatted incorrectly
JSON numbers have specific rules. Leading zeros are not allowed (07 is invalid, use 7). Trailing decimal points are not allowed (1. is invalid, use 1.0 or 1). Numbers must not use commas as thousand separators (1,000 is invalid, use 1000). Scientific notation is supported (1.5e10 is valid).
// INVALID
{"price": 1,299.00, "count": 07, "ratio": 1.}
// VALID
{"price": 1299.00, "count": 7, "ratio": 1.0}
JSON Validation Across Different Tools and Languages
Browser console (Chrome/Firefox DevTools)
// Paste into console and press Enter
JSON.parse('{"name": "Maria", "role": "admin"}');
// Returns: {name: "Maria", role: "admin"} if valid
// Throws: SyntaxError: Unexpected token if invalid
Python command line
python3 -m json.tool data.json
# Outputs formatted JSON if valid
# Outputs "json.decoder.JSONDecodeError: ..." with line number if invalid
# Validate without formatting
python3 -c "import json; json.load(open('data.json'))"
Node.js
node -e "JSON.parse(require('fs').readFileSync('data.json','utf8')); console.log('Valid')"
Linux/Mac command line with jq
jq . data.json # formats and validates jq empty data.json # validates only, no output if valid echo $? # 0 = valid, 1 = invalid
Validating JSON in Code (Production Patterns)
Never let a JSON parse error crash your application without a useful error message. Wrap all JSON parsing in proper error handling and log the raw input when validation fails — this is the only way to debug JSON errors in production.
// JavaScript — safe parse with logging
function safeParse(text, context = 'unknown') {
try {
return { data: JSON.parse(text), error: null };
} catch (err) {
console.error(`JSON parse error in ${context}:`, err.message);
console.error('Raw input (first 200 chars):', String(text).slice(0, 200));
return { data: null, error: err.message };
}
}
const { data, error } = safeParse(apiResponse, 'user endpoint');
if (error) {
// handle gracefully
}
// Python — safe parse with logging
import json, logging
def safe_parse(text, context='unknown'):
try:
return json.loads(text)
except json.JSONDecodeError as e:
logging.error(f"JSON parse error in {context}: {e}")
logging.error(f"Input preview: {str(text)[:200]}")
return None
JSON Schema Validation (Catching Structural Errors)
Syntax validation (is this valid JSON?) is just the first layer. Schema validation (does this JSON have the right structure and types?) catches a second class of problems: a required field is missing, a number field contains a string, an array is empty when it should have items.
// JavaScript — JSON Schema validation with Ajv
import Ajv from 'ajv'; // npm install ajv
const ajv = new Ajv();
const schema = {
type: 'object',
required: ['name', 'email', 'role'],
properties: {
name: { type: 'string', minLength: 1 },
email: { type: 'string', format: 'email' },
role: { type: 'string', enum: ['admin', 'editor', 'viewer'] },
age: { type: 'integer', minimum: 0 }
},
additionalProperties: false
};
const validate = ajv.compile(schema);
const valid = validate(data);
if (!valid) {
console.log(validate.errors);
// [{instancePath: '/email', message: 'must match format "email"'}]
}
Frequently Asked Questions
How do I validate JSON without sending it to an external tool?
Use your terminal: python3 -m json.tool yourfile.json validates and formats the file entirely locally. In VS Code, open a .json file — the editor validates it automatically and underlines errors. In Node.js: JSON.parse(fs.readFileSync('file.json', 'utf8')) throws a descriptive error if invalid.
Why does my JSON work in JavaScript but fail in other languages?
JavaScript is lenient about JSON. Some JavaScript engines accept trailing commas, single quotes, and comments in JSON-like data — features that are not part of the JSON specification. A strict JSON parser in Python, Java, or Go will reject these. The safest approach: validate with python3 -m json.tool or ToolPry's formatter before assuming your JSON is correct.
Can I fix invalid JSON automatically?
The json-repair npm package and similar tools attempt to fix common errors — trailing commas, single quotes, unquoted keys, truncated responses. These are useful for processing JSON from sources you do not control (scraped data, logs, user input). For JSON you generate yourself, fix the source rather than the output: use your language's JSON serialiser and never build JSON strings through string concatenation.
What is the difference between JSON and JSON5?
JSON5 is a non-standard extension that adds comments, trailing commas, single quotes, unquoted keys, multi-line strings, and hexadecimal numbers to JSON. It is used in some configuration files (.json5 extension). Standard JSON parsers reject JSON5 syntax. If your file uses JSON5 features, use a JSON5 parser library rather than the standard JSON.parse().