5 Common JSON Syntax Errors and How to Fix Them
Master JSON syntax with this definitive guide to the 5 most common errors developers encounter. Learn to identify, fix, and prevent JSON validation issues with practical examples and pro tips.
Big JSON Team
• Technical WriterExpert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.
# 5 Common JSON Syntax Errors and How to Fix Them
JSON (JavaScript Object Notation) is everywhere in modern web development—from API responses to configuration files. Despite its simple syntax, developers constantly encounter frustrating JSON errors that break applications.
This guide covers the 5 most common JSON syntax errors you'll encounter, how to identify them instantly, and how to fix them permanently.
---
Why JSON Errors Are So Common
JSON's strict syntax requirements mean even a single misplaced character can invalidate an entire document. Unlike JavaScript, JSON:
- ✅ Requires double quotes for strings (single quotes are invalid)
- ✅ Prohibits trailing commas
- ✅ Mandates exact formatting for keys and values
- ✅ Allows no comments whatsoever
Let's dive into the errors that trip up developers most frequently.
---
Error #1: Trailing Commas (The Silent Killer)
The Problem
Trailing commas—extra commas after the last item in an array or object—are perfectly valid in JavaScript but completely forbidden in JSON.
❌ Invalid JSON
{
"username": "alice123",
"email": "alice@example.com",
"active": true,
}
{
"products": [
{ "id": 1, "name": "Laptop" },
{ "id": 2, "name": "Mouse" },
{ "id": 3, "name": "Keyboard" },
]
}
✅ Valid JSON
{
"username": "alice123",
"email": "alice@example.com",
"active": true
}
{
"products": [
{ "id": 1, "name": "Laptop" },
{ "id": 2, "name": "Mouse" },
{ "id": 3, "name": "Keyboard" }
]
}
Error Message You'll See
Unexpected token } in JSON at position 78
SyntaxError: Trailing comma in JSON
How to Fix It
Manual Fix:} or brackets ]// In your code editor, search for these patterns:
,\s} // Comma before closing brace
,\s] // Comma before closing bracket
---
Error #2: Single Quotes Instead of Double Quotes
The Problem
JavaScript allows both single and double quotes for strings, but JSON only accepts double quotes ("). Using single quotes is one of the most common mistakes when converting JavaScript objects to JSON.
❌ Invalid JSON
{
'name': 'John Doe',
'age': 30,
'city': 'New York'
}
{
"name": 'John Doe',
"age": 30
}
✅ Valid JSON
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
Error Message You'll See
Unexpected token ' in JSON at position 2
SyntaxError: Expected property name or '}' in JSON
How to Fix It
Quick Fix:// JavaScript: Convert single to double quotes
const fixedJson = invalidJson.replace(/'/g, '"');
Better Approach: Use proper JSON serialization:
// Instead of manually writing JSON with quotes:
const wrong = "{ 'name': 'John' }"; // ❌
// Use JSON.stringify():
const obj = { name: 'John' };
const correct = JSON.stringify(obj); // ✅ "{"name":"John"}"
When This Error Happens
- Copying JavaScript object literals and forgetting to convert quotes
- Manually typing JSON without a proper editor
- Using template literals incorrectly
---
Error #3: Unquoted Keys
The Problem
In JavaScript, object keys can be unquoted if they're valid identifiers. JSON requires all keys to be strings wrapped in double quotes.
❌ Invalid JSON
{
name: "Alice",
age: 28,
isActive: true
}
{
user_id: 42,
"email": "test@example.com"
}
✅ Valid JSON
{
"name": "Alice",
"age": 28,
"isActive": true
}
{
"user_id": 42,
"email": "test@example.com"
}
Error Message You'll See
Unexpected token n in JSON at position 4
SyntaxError: Expected property name enclosed in double quotes
How to Fix It
Visual Studio Code Users:Find: (\\w+):\\s
Replace: "$1":
Real-World Example
// Common mistake when logging:
console.log({ status: 'success', data: result }); // Valid JS ✅
// Trying to save this as JSON:
{
status: "success", // ❌ Invalid JSON
data: { ... }
}
// Correct JSON:
{
"status": "success", // ✅
"data": { ... }
}
---
Error #4: Invalid Escape Sequences
The Problem
JSON supports limited escape sequences. Using invalid ones or forgetting to escape special characters causes parsing errors.
❌ Invalid JSON
{
"path": "C:\\Users\\Alice\\Documents",
"message": "Line 1
Line 2"
}
{
"quote": "He said "hello" to me"
}
✅ Valid JSON
{
"path": "C:\\\\Users\\\\Alice\\\\Documents",
"message": "Line 1\nLine 2"
}
{
"quote": "He said \"hello\" to me"
}
Valid Escape Sequences in JSON
| Character | Escape Sequence | Description |
|-----------|----------------|-------------|
| " | \" | Double quote |
| \ | \\\\ | Backslash |
| / | \/ | Forward slash |
| Newline | \n | Line feed |
| Tab | \t | Horizontal tab |
| Carriage return | \r | Carriage return |
| Backspace | \b | Backspace |
| Form feed | \f | Form feed |
| Unicode | \uXXXX | Unicode character |
Error Message You'll See
Unexpected token in JSON at position 25
SyntaxError: Invalid escape sequence
How to Fix It
JavaScript Escaping:// Automatically handle escaping:
const data = {
path: "C:\\Users\\Alice",
message: "Line 1\nLine 2"
};
const json = JSON.stringify(data);
// Result: {"path":"C:\\\\Users\\\\Alice","message":"Line 1\\nLine 2"}
Manual Path Escaping:
const windowsPath = "C:\\Users\\Alice";
const jsonPath = windowsPath.replace(/\\/g, "\\\\\\\\");
---
Error #5: Comments in JSON (JSON ≠ JavaScript!)
The Problem
Developers often add comments to JSON files for documentation, but JSON does not support comments of any kind. No //, no / /, nothing.
❌ Invalid JSON
{
// User configuration
"username": "admin",
"role": "superuser",
/ This is temporary
Remove in production /
"debugMode": true
}
✅ Valid JSON (No Comments Allowed)
{
"username": "admin",
"role": "superuser",
"debugMode": true
}
Error Message You'll See
Unexpected token / in JSON at position 4
SyntaxError: JSON does not support comments
Workarounds
Option 1: Use a Comment Field{
"_comment": "User configuration - update before production",
"username": "admin",
"role": "superuser",
"debugMode": true
}
Option 2: Use JSON5 or JSONC
For configuration files, consider:
- JSON5: Supports comments, trailing commas, and more
- JSONC: JSON with Comments (used by VS Code)
// config.json5
{
// User configuration
username: "admin", // No quotes needed
role: "superuser",
debugMode: true, // Trailing comma OK!
}
Option 3: Separate Documentation File
project/
├── config.json # Pure JSON
├── config.README.md # Documentation with comments
---
Bonus: How to Catch JSON Errors Early
1. Use Online Validators
BigJSON Validator - Instant validation with helpful error messages:- Paste your JSON
- Get line-by-line error detection
- See exactly where the problem is
2. IDE Extensions
VS Code:- Built-in JSON validation
- Install "Error Lens" for inline error messages
- JSONLint package
- linter-jsonlint
3. Pre-Commit Hooks
# .git/hooks/pre-commit
#!/bin/bash
for file in $(git diff --cached --name-only | grep -E '\.json$'); do
if ! python -m json.tool "$file" > /dev/null 2>&1; then
echo "Invalid JSON in $file"
exit 1
fi
done
4. Automated Testing
// Jest test
test('config.json is valid', () => {
const fs = require('fs');
const config = fs.readFileSync('config.json', 'utf8');
expect(() => {
JSON.parse(config);
}).not.toThrow();
});
---
Quick Reference: Error Detection Checklist
Before submitting or deploying JSON files, check:
- [ ] No trailing commas after last items
- [ ] All strings use double quotes (
") - [ ] All object keys are quoted
- [ ] Special characters are properly escaped
- [ ] No comments anywhere
- [ ] Proper nesting of brackets and braces
- [ ] Valid data types (string, number, boolean, null, object, array)
- [ ] Numbers don't have leading zeros (except
0.x)
---
Tools to Prevent JSON Errors
1. BigJSON Online Tools
Visit BigJSON for:
- Formatter: Auto-fix formatting issues
- Validator: Instant syntax checking
- Minifier: Remove whitespace for production
2. Command-Line Tools
# Node.js built-in validator
node -e "JSON.parse(require('fs').readFileSync('file.json'))"
# Python validator
python -m json.tool file.json
# jq (JSON processor)
jq . file.json
3. Browser Developer Tools
// Console validation
try {
JSON.parse(jsonString);
console.log('✅ Valid JSON');
} catch (e) {
console.error('❌ Invalid:', e.message);
}
---
Common Error Messages Decoded
| Error Message | Likely Cause | Fix |
|--------------|-------------|-----|
| Unexpected token , | Trailing comma | Remove comma before } or ] |
| Unexpected token ' | Single quotes | Replace with double quotes |
| Expected property name | Unquoted key | Quote all object keys |
| Unexpected token } | Missing comma | Add comma between items |
| Unexpected end of JSON | Unclosed brace/bracket | Check nesting |
| Invalid escape sequence | Wrong escape character | Use valid escapes (\\, \n, etc.) |
---
Real-World Example: Debugging an API Response
Let's fix a real API response with multiple errors:
❌ Before (Invalid)
{
success: true, // Error: Unquoted key
'message': 'Data retrieved', // Error: Single quotes
data: [
{
id: 1,
name: "Product A",
price: 29.99,
}, // Error: Trailing comma
{
id: 2,
name: "Product B",
// Note: Special offer // Error: Comment
price: 19.99
}
], // Error: Trailing comma
}
✅ After (Valid)
{
"success": true,
"message": "Data retrieved",
"data": [
{
"id": 1,
"name": "Product A",
"price": 29.99
},
{
"id": 2,
"name": "Product B",
"price": 19.99
}
]
}
---
Preventing Errors in Your Workflow
For Developers
// Always use JSON.stringify() instead of manual concatenation
const config = {
apiKey: process.env.API_KEY,
timeout: 5000
};
// ❌ Manual (error-prone)
const json = '{ "apiKey": "' + config.apiKey + '", "timeout": ' + config.timeout + ' }';
// ✅ Automatic (safe)
const json = JSON.stringify(config);
For Configuration Files
For API Responses
// Express.js example
app.get('/api/data', (req, res) => {
const data = { status: 'ok', results: [...] };
// ❌ Manual string building
res.send('{"status":"' + data.status + '"}');
// ✅ Automatic JSON serialization
res.json(data); // Handles escaping, quotes, etc.
});
---
Conclusion
The 5 most common JSON syntax errors are:
} and ]")Next Steps
Got questions about JSON errors? Drop a comment below!
---
Related Resources
- Common JSON Errors and How to Fix Them
- How to Format JSON Files
- JSON Validator Tool
- JSON Formatter Online
---
Last updated: February 15, 2026Related Articles
How to Format JSON: Pretty Print and Beautify Guide 2026
Learn how to format and beautify JSON using command-line tools, code editors, online formatters, and programming languages. Complete guide with examples.
Common JSON Errors and How to Fix Them
Troubleshoot JSON syntax errors with this complete guide. Learn to identify and fix the most common JSON validation problems.