Common JSON Errors and How to Debug Them
JSON errors can be frustrating, especially when error messages are cryptic. This guide covers the most common JSON errors and provides practical solutions for debugging them.
1. Missing or Mismatched Quotes
Error: Property names and string values must use double quotes.
// WRONG
{
name: "John",
'email': 'john@example.com'
}
// CORRECT
{
"name": "John",
"email": "john@example.com"
}
2. Trailing Commas
Error: JSON does not allow trailing commas after the last item in arrays or objects.
// WRONG
{
"items": [1, 2, 3,],
"name": "John",
}
// CORRECT
{
"items": [1, 2, 3],
"name": "John"
}
3. Missing Commas
Error: Commas are required between items in arrays and objects.
// WRONG
{
"name": "John"
"age": 30
}
// CORRECT
{
"name": "John",
"age": 30
}
4. Unescaped Special Characters
Error: Special characters in strings must be escaped.
// WRONG
{
"message": "He said "Hello"",
"path": "C:\Users\Documents"
}
// CORRECT
{
"message": "He said \"Hello\"",
"path": "C:\\Users\\Documents"
}
5. Invalid Number Formats
Error: Numbers must be valid JSON numbers.
// WRONG
{
"price": 19.99.99,
"hex": 0xFF,
"nan": NaN,
"infinity": Infinity
}
// CORRECT
{
"price": 19.99,
"hex": 255,
"nan": null,
"infinity": null
}
6. Mismatched Brackets
Error: All brackets must be properly matched and nested.
// WRONG
{
"users": [
{"name": "John"}
,
"count": 1
}
// CORRECT
{
"users": [
{"name": "John"}
],
"count": 1
}
7. Using undefined
Error: undefined is not a valid JSON value.
// WRONG
{
"name": undefined
}
// CORRECT
{
"name": null
}
// Or omit the field entirely
{}
Debugging Tips
1. Use Online Validators
Use our JSON Doctor tool to quickly validate and format your JSON. It will highlight errors and show you exactly where the problem is.
2. Check Character by Character
function findJsonError(json) {
try {
JSON.parse(json);
return "Valid JSON";
} catch (e) {
const match = e.message.match(/position (\d+)/);
if (match) {
const pos = parseInt(match[1]);
const context = json.substring(Math.max(0, pos - 20), pos + 20);
return `Error at position ${pos}: ...${context}...`;
}
return e.message;
}
}
3. Use a Linter
Install a JSON linter in your IDE to catch errors as you type.
4. Pretty Print for Clarity
const ugly = '{"name":"John","age":30}';
const pretty = JSON.stringify(JSON.parse(ugly), null, 2);
console.log(pretty);
Common Error Messages
- Unexpected token: Usually a syntax error like missing quotes or commas
- Unexpected end of JSON: Missing closing brackets or incomplete JSON
- Unexpected number: Invalid number format
- Expected property name: Missing or invalid property name