There's nothing more frustrating than hitting a JSON syntax error that breaks your application. Whether you're working with APIs, configuration files, or data processing, JSON errors can stop you in your tracks.
In this comprehensive guide, we'll cover the most common JSON syntax errors, how to identify them, and exactly how to fix them. By the end, you'll be able to debug any JSON issue like a pro!
Table of Contents
- Understanding JSON Errors
- Error 1: Trailing Commas
- Error 2: Single Quotes
- Error 3: Unquoted Keys
- Error 4: Comments in JSON
- Error 5: Special Characters
- Error 6: Encoding Issues
- Error 7: Undefined and NaN Values
- Error 8: Bracket Mismatch
- Best Tools for Fixing JSON Errors
Understanding JSON Errors
Before diving into specific errors, let's understand how JSON parsing works:
try {
const data = JSON.parse(jsonString);
console.log('Valid JSON!', data);
} catch (error) {
console.error('JSON Error:', error.message);
// Example: "Unexpected token } at position 45"
}
Error messages typically include:
- Unexpected token: The parser found a character it didn't expect
- Position: The character index where the error occurred
- Line/Column: Some parsers provide line and column numbers
Error 1: Trailing Commas
This is the #1 most common JSON error. A trailing comma is a comma after the last item in an object or array.
The Error
// β INVALID - Trailing comma after "age"
{
"name": "Alice",
"age": 25,
}
// β INVALID - Trailing comma in array
{
"colors": ["red", "green", "blue",]
}
The Fix
// β
VALID - No trailing comma
{
"name": "Alice",
"age": 25
}
// β
VALID - No trailing comma in array
{
"colors": ["red", "green", "blue"]
}
Why This Happens
Trailing commas are allowed in JavaScript objects and arrays, so developers often accidentally include them in JSON. Remember: JSON is stricter than JavaScript!
Prevention Tips
// Use JSON.stringify to ensure valid output
const obj = {name: "Alice", age: 25};
const validJson = JSON.stringify(obj, null, 2);
// This will never have trailing commas
Error 2: Single Quotes
JSON requires double quotes for strings. Single quotes are not valid.
The Error
// β INVALID - Single quotes
{'name': 'Alice', 'age': 25}
// β INVALID - Mixed quotes
{"name": 'Alice', "age": 25}
The Fix
// β
VALID - Double quotes only
{"name": "Alice", "age": 25}
Quick Fix Script
// Replace single quotes with double quotes
function fixQuotes(jsonString) {
// Be careful - this is a simple fix and may not work in all cases
return jsonString.replace(/'/g, '"');
}
const fixed = fixQuotes("{'name': 'Alice'}");
console.log(fixed); // {"name": "Alice"}
Error 3: Unquoted Keys
In JSON, all keys MUST be strings enclosed in double quotes.
The Error
// β INVALID - Unquoted keys
{name: "Alice", age: 25}
// β INVALID - Number as key (valid in JS, not in JSON)
{1: "first", 2: "second"}
The Fix
// β
VALID - All keys quoted
{"name": "Alice", "age": 25}
// β
VALID - Number keys as strings
{"1": "first", "2": "second"}
JavaScript vs JSON
// JavaScript object - unquoted keys are fine
const jsObj = {name: "Alice", age: 25};
// JSON string - must quote all keys
const jsonStr = '{"name": "Alice", "age": 25}';
Error 4: Comments in JSON
JSON does NOT support comments. Any form of comment will cause a parse error.
The Error
// β INVALID - JavaScript-style comments
{
"name": "Alice", // User's name
"age": 25 /* User's age */
}
// β INVALID - HTML-style comments
{
<!-- Configuration -->
"debug": true
}
The Fix
// β
VALID - No comments allowed
{
"name": "Alice",
"age": 25
}
Workarounds for Comments
Option 1: Use a description field
{
"_comment": "This is a configuration file",
"_description": "Debug mode enables verbose logging",
"debug": true
}
Option 2: Use JSON5 (superset of JSON)
// JSON5 supports comments
const JSON5 = require('json5');
const config = JSON5.parse(`{
// This is a comment
"debug": true,
}`);
Option 3: Use JSONC (JSON with Comments) in VS Code
VS Code supports .jsonc files that allow comments for configuration.
Error 5: Special Characters
Certain characters must be escaped in JSON strings.
The Error
// β INVALID - Unescaped special characters
{
"path": "C:\Users\Alice",
"message": "She said "Hello"",
"text": "Line 1
Line 2"
}
The Fix
// β
VALID - Properly escaped
{
"path": "C:\\Users\\Alice",
"message": "She said \"Hello\"",
"text": "Line 1\nLine 2"
}
Escape Character Reference
| Character | Escape Sequence |
|---|---|
| Backslash \ | \\ |
| Double Quote " | \" |
| Newline | \n |
| Tab | \t |
| Carriage Return | \r |
| Unicode | \uXXXX |
Auto-Escaping with JSON.stringify
const data = {
path: 'C:\Users\Alice',
message: 'She said "Hello"'
};
const json = JSON.stringify(data, null, 2);
// Automatically escaped correctly
Error 6: Encoding Issues
JSON should be encoded in UTF-8. Other encodings can cause parse errors.
The Error
// β INVALID - BOM character at start
{Γ―ΒΏΒΏ"name": "Alice"}
// β INVALID - Invalid UTF-8 sequences
{"name": "ΓΏΓΎ"}
The Fix
# Python: Ensure UTF-8 encoding
import json
# Read with UTF-8 encoding
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# Write with UTF-8 encoding
with open('output.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
// Node.js: Handle BOM
const fs = require('fs');
let content = fs.readFileSync('data.json', 'utf-8');
// Remove BOM if present
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
const data = JSON.parse(content);
Error 7: Undefined and NaN Values
JSON doesn't support JavaScript's undefined, NaN, or Infinity.
The Error
// β INVALID - undefined is not valid
{"value": undefined}
// β INVALID - NaN is not valid
{"value": NaN}
// β INVALID - Infinity is not valid
{"value": Infinity}
The Fix
// β
VALID - Use null for missing values
{"value": null}
// β
VALID - Use string for special numbers
{"value": "NaN"}
// β
VALID - Or use a very large number
{"value": 1e308}
JavaScript Conversion
const data = {
a: undefined,
b: NaN,
c: Infinity
};
// JSON.stringify handles these automatically
const json = JSON.stringify(data);
// Result: {"b":null,"c":null}
// Note: undefined properties are omitted entirely
Error 8: Bracket Mismatch
Mismatched or unclosed brackets are a common source of errors.
The Error
// β INVALID - Missing closing brace
{
"name": "Alice",
"items": [1, 2, 3]
// β INVALID - Wrong bracket type
{
"items": [1, 2, 3}
]
The Fix
// β
VALID - Properly matched brackets
{
"name": "Alice",
"items": [1, 2, 3]
}
Counting Brackets
function validateBrackets(json) {
let braces = 0;
let brackets = 0;
for (const char of json) {
if (char === '{') braces++;
if (char === '}') braces--;
if (char === '[') brackets++;
if (char === ']') brackets--;
}
if (braces !== 0) console.error('Mismatched curly braces');
if (brackets !== 0) console.error('Mismatched square brackets');
return braces === 0 && brackets === 0;
}
Best Tools for Fixing JSON Errors
1. Online JSON Validators
- JSON Formatter Pro - Validates, formats, and shows error locations
- JSONLint - Simple online validator
- JSON Editor Online - Visual tree view with error highlighting
2. IDE Extensions
- VS Code: Built-in JSON validation with error squiggles
- JetBrains IDEs: Automatic syntax checking
- Sublime Text: Pretty JSON package
3. Command Line Tools
# Validate JSON with jq
jq . data.json
# Python validation
python -m json.tool data.json
# Node.js
node -e "require('./data.json')"
4. Programmatic Validation
function validateJson(str) {
try {
JSON.parse(str);
return { valid: true };
} catch (error) {
return {
valid: false,
error: error.message,
position: error.message.match(/position (\d+)/)?.[1]
};
}
}
console.log(validateJson('{"name": "Alice"}'));
// { valid: true }
console.log(validateJson('{"name": "Alice",}'));
// { valid: false, error: "Unexpected token...", position: "18" }
Quick Reference: JSON Syntax Checklist
- βοΈ All keys are double-quoted strings
- βοΈ All string values use double quotes
- βοΈ No trailing commas
- βοΈ No comments
- βοΈ Special characters are escaped
- βοΈ All brackets are properly matched
- βοΈ No undefined, NaN, or Infinity values
- βοΈ UTF-8 encoding without BOM
Conclusion
JSON errors can be frustrating, but they're almost always easy to fix once you know what to look for. Remember these key points:
- Double quotes only - Never use single quotes
- No trailing commas - Remove that last comma
- No comments - JSON doesn't support them
- Escape special characters - Backslash, quotes, newlines
- Use validation tools - Let the computer find errors for you
Use our free JSON Formatter Pro tool to validate and fix your JSON instantly!