JSON Errors Guide: Common & Complex Validation Errors
JSON errors can be frustrating and time-consuming to debug. This comprehensive guide covers the most common JSON errors developers encounter, from simple syntax mistakes to complex validation issues, with clear examples and solutions for each.
🛠️ Quick Fix Tool
🚀 Start validating your JSON to instantly identify and locate JSON errors with detailed error messages and line numbers.
Most Common JSON Errors (90% of Issues)
1. Trailing Comma Error
Error Message: "Unexpected token ," or "Trailing comma in object/array"
// ❌ Invalid - trailing comma
{
"name": "John",
"age": 30,
"city": "New York", ← Extra comma here
}
// ❌ Invalid - trailing comma in array
[
"apple",
"banana",
"orange", ← Extra comma here
]
// ✅ Valid - no trailing commas
{
"name": "John",
"age": 30,
"city": "New York"
}
// ✅ Valid array
[
"apple",
"banana",
"orange"
]
⚠️ Why This Happens
Many programming languages allow trailing commas, but JSON specification strictly forbids them. This is the #1 cause of JSON validation failures.
2. Single Quotes Instead of Double Quotes
Error Message: "Unexpected token '" or "Invalid character"
// ❌ Invalid - single quotes
{
'name': 'John',
'age': 30
}
// ❌ Invalid - mixed quotes
{
"name": 'John',
"age": 30
}
// ✅ Valid - double quotes only
{
"name": "John",
"age": 30
}
3. Unquoted Object Keys
Error Message: "Unexpected token" or "Expected property name"
// ❌ Invalid - unquoted keys
{
name: "John",
age: 30,
isActive: true
}
// ✅ Valid - quoted keys
{
"name": "John",
"age": 30,
"isActive": true
}
4. Missing Quotes Around Strings
Error Message: "Unexpected token" or "Invalid value"
// ❌ Invalid - unquoted string values
{
"name": John,
"city": New York,
"status": active
}
// ✅ Valid - quoted string values
{
"name": "John",
"city": "New York",
"status": "active"
}
5. Comments in JSON
Error Message: "Unexpected token /" or "Invalid character"
// ❌ Invalid - comments not allowed
{
"name": "John", // This is a comment
/* Multi-line comment */
"age": 30
}
// ✅ Valid - no comments
{
"name": "John",
"age": 30
}
Intermediate JSON Errors
6. Incorrect Boolean/Null Values
Error Message: "Unexpected token" or "Invalid literal"
// ❌ Invalid - incorrect case
{
"isActive": True,
"isDeleted": FALSE,
"middleName": NULL,
"isVerified": undefined
}
// ✅ Valid - correct case and values
{
"isActive": true,
"isDeleted": false,
"middleName": null,
"isVerified": null
}
7. Invalid Number Formats
Error Message: "Unexpected token" or "Invalid number"
// ❌ Invalid - leading zeros, hex, infinity
{
"id": 007,
"hex": 0xFF,
"infinite": Infinity,
"notNumber": NaN,
"decimal": .5
}
// ✅ Valid - proper number formats
{
"id": 7,
"hex": 255,
"infinite": null,
"notNumber": null,
"decimal": 0.5
}
8. Mismatched Brackets and Braces
Error Message: "Unexpected end of JSON input" or "Expected '}'"
// ❌ Invalid - mismatched brackets
{
"users": [
{
"name": "John",
"hobbies": ["reading", "coding"
}
]
} ← Missing closing bracket for hobbies array
// ✅ Valid - properly matched
{
"users": [
{
"name": "John",
"hobbies": ["reading", "coding"]
}
]
}
Advanced JSON Errors
9. Unicode and Escape Sequence Errors
Error Message: "Invalid escape sequence" or "Invalid Unicode"
// ❌ Invalid - incorrect escape sequences
{
"path": "C:\new\folder", ← Unescaped backslashes
"quote": "He said "Hello"", ← Unescaped quotes
"unicode": "\u12GH" ← Invalid Unicode
}
// ✅ Valid - properly escaped
{
"path": "C:\\new\\folder",
"quote": "He said \\"Hello\\"",
"unicode": "\\u0041" // or just "A"
}
10. Circular Reference Errors (Serialization)
Error Message: "Converting circular structure to JSON"
// ❌ JavaScript code that causes circular reference
const obj = { name: "John" };
obj.self = obj; // Creates circular reference
JSON.stringify(obj); // Throws error
// ✅ Solution - remove circular references
const obj = { name: "John" };
const cleanObj = { ...obj };
delete cleanObj.self;
JSON.stringify(cleanObj);
11. Large Number Precision Issues
Error Message: Silent data corruption or precision loss
// ⚠️ Problematic - numbers too large for JavaScript
{
"bigInteger": 9007199254740992, // Beyond safe integer
"id": 1234567890123456789, // Will lose precision
"timestamp": 1640995200000000 // Microseconds - too large
}
// ✅ Solution - use strings for large numbers
{
"bigInteger": "9007199254740992",
"id": "1234567890123456789",
"timestamp": "1640995200000000"
}
Complex Validation Errors
12. Schema Validation Failures
Error Message: Various schema-specific errors
// Schema definition
{
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"age": { "type": "integer", "minimum": 0, "maximum": 150 }
},
"required": ["email"]
}
// ❌ Invalid data against schema
{
"email": "not-an-email", // Invalid email format
"age": -5 // Below minimum
}
// Missing required "email" field
// ✅ Valid data against schema
{
"email": "user@example.com",
"age": 25
}
13. Encoding and Character Set Issues
Error Message: "Invalid character" or encoding errors
// ❌ Problematic - mixed encodings or invalid characters
{
"name": "José", // May cause issues if not UTF-8
"text": "Hello World", // Null character
"emoji": "😀" // May need proper encoding
}
// ✅ Solution - ensure UTF-8 encoding
{
"name": "José",
"text": "Hello World",
"emoji": "😀"
}
14. Deeply Nested Structure Limits
Error Message: "Maximum call stack exceeded" or "Too deeply nested"
// ❌ Problematic - extremely deep nesting (100+ levels)
{
"level1": {
"level2": {
"level3": {
// ... continues for 100+ levels
"level100": {
"data": "value"
}
}
}
}
}
// ✅ Better - flatter structure
{
"path": "level1.level2.level3...level100",
"data": "value",
"depth": 100
}
Error Detection Strategies
Using JSON Validators
🔍 Validation Tools
- JSONly Viewer - Real-time validation with line numbers
- JSONLint - Online JSON validator
- VS Code - Built-in JSON validation
- Command line tools - jq, python -m json.tool
Common Error Patterns
- Line-by-line validation - Check each line for syntax
- Bracket matching - Ensure all brackets/braces are paired
- Quote consistency - Use only double quotes
- Comma placement - No trailing commas
- Data type validation - Ensure correct types
Debugging Complex JSON Errors
Binary Search Method
// For large JSON files with unclear errors:
// 1. Split the JSON in half
// 2. Test each half separately
// 3. Continue splitting the problematic half
// 4. Repeat until you isolate the error
Programmatic Validation
// JavaScript validation with detailed errors
function validateJSON(jsonString) {
try {
JSON.parse(jsonString);
return { valid: true };
} catch (error) {
return {
valid: false,
error: error.message,
position: error.message.match(/position (d+)/)?.[1]
};
}
}
// Usage
const result = validateJSON('{"name": "John",}');
console.log(result);
// { valid: false, error: "Unexpected token }", position: "16" }
Prevention Best Practices
Development Practices
- Use JSON schema validation - Define and validate structure
- Implement linting - Catch errors during development
- Use proper JSON libraries - Avoid manual string construction
- Test with edge cases - Include unusual data in tests
- Validate at boundaries - Check data at API endpoints
Code Generation
// ✅ Good - use proper JSON methods
const data = {
name: "John",
age: 30,
hobbies: ["reading", "coding"]
};
const jsonString = JSON.stringify(data, null, 2);
// ❌ Bad - manual string construction
const jsonString = '{"name": "' + name + '", "age": ' + age + '}';
// Prone to syntax errors and injection issues
Error Recovery Strategies
Graceful Error Handling
// Robust JSON parsing with fallbacks
function safeJSONParse(jsonString, fallback = null) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error('JSON Parse Error:', error.message);
// Attempt to fix common issues
const cleaned = jsonString
.replace(/,(s*[}]])/g, '$1') // Remove trailing commas
.replace(/'/g, '"'); // Replace single quotes
try {
return JSON.parse(cleaned);
} catch (secondError) {
console.error('JSON still invalid after cleanup');
return fallback;
}
}
}
Partial Data Recovery
// Extract valid parts from corrupted JSON
function extractValidJSON(corruptedJSON) {
const lines = corruptedJSON.split('
');
let validParts = [];
for (let i = 0; i < lines.length; i++) {
try {
const partial = lines.slice(0, i + 1).join('
') + '
}';
JSON.parse(partial);
validParts.push(lines[i]);
} catch (error) {
// Skip invalid lines
}
}
return validParts.join('
');
}
Tools and Resources
Online Validators
- JSONly Viewer - Advanced validation with tree view
- JSONLint - Simple online validator
- JSON Formatter - Validation with formatting
Command Line Tools
# Python JSON validation
python -m json.tool input.json
# jq validation and formatting
jq . input.json
# Node.js validation
node -e "JSON.parse(require('fs').readFileSync('input.json', 'utf8'))"
IDE Extensions
- VS Code - Built-in JSON validation and formatting
- Sublime Text - Pretty JSON plugin
- Atom - JSON validation packages
Performance Considerations
⚠️ Large JSON Performance Issues
- Memory usage - Large JSON files consume significant RAM
- Parse time - Complex structures take longer to validate
- Browser limits - Browsers may timeout on huge files
- Network transfer - Large JSON affects API performance
Optimization Strategies
- Stream processing - Parse JSON in chunks
- Compression - Use gzip for network transfer
- Pagination - Break large datasets into pages
- Selective parsing - Parse only needed fields
Conclusion
JSON errors range from simple syntax mistakes to complex validation and performance issues. Understanding these common patterns and having the right tools can save hours of debugging time.
Remember:
- 90% of JSON errors are simple syntax issues (trailing commas, quotes)
- Use validation tools early and often in development
- Implement proper error handling for production systems
- Test with edge cases to catch complex issues
Need help debugging JSON errors? 🚀 Start validating your JSON for instant error detection with detailed messages and line numbers.
📚 Related Resources
- Complete JSON Guide - Master JSON syntax and validation
- JSON Tools - Discover the best JSON utilities
- API Documentation - JSON API best practices