Common JSON Errors and How to Fix Them
📅 January 2025⏱️ 14 min read📚 Beginner
Introduction: Debugging JSON Like a Pro
JSON errors are frustrating but usually easy to fix once you know what to look for. This comprehensive guide covers the most common JSON errors, their causes, and step-by-step solutions. Whether you're debugging API responses, configuration files, or data imports, this guide will help you solve JSON issues quickly.
1. SyntaxError: Unexpected Token
This is the most common JSON error, occurring when the JSON parser encounters invalid syntax.
Error 1.1: Missing or Extra Quotes
❌ Wrong
{
name: "Alice",
'email': 'alice@example.com'
}
Error: Keys must use double quotes, not single quotes or no quotes
✅ Correct
{
"name": "Alice",
"email": "alice@example.com"
}
All keys and string values use double quotes
Error 1.2: Trailing Commas
❌ Wrong
{
"name": "Alice",
"age": 30,
"email": "alice@example.com",
}
Error: Trailing comma after last property
✅ Correct
{
"name": "Alice",
"age": 30,
"email": "alice@example.com"
}
No comma after last property
Error 1.3: Comments in JSON
❌ Wrong
{
// User information
"name": "Alice",
/* Age in years */
"age": 30
}
Error: JSON doesn't support comments
✅ Correct
{
"_comment": "User information",
"name": "Alice",
"age": 30,
"_ageNote": "Age in years"
}
Use special keys for documentation
Error 1.4: Unescaped Special Characters
Common Error
{"message": "He said "Hello" to me"}
// Error: Unescaped quotes inside string
Solution
{"message": "He said \"Hello\" to me"}
// Escape quotes with backslash
// Other special characters that need escaping:
{
"backslash": "C:\\Users\\Alice",
"newline": "Line 1\nLine 2",
"tab": "Col1\tCol2",
"unicode": "Copyright \u00A9"
}
2. SyntaxError: Unexpected End of JSON Input
This error occurs when the JSON is incomplete or truncated.
Incomplete JSON
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"
// Missing closing brace and bracket!
How to Fix
- Count opening and closing braces/brackets
- Use a JSON validator to identify where syntax breaks
- Check if file was truncated during transmission
- Verify the entire response was received
{
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
}
3. Invalid Data Types
Error 3.1: Undefined Values
❌ Wrong
{
"name": "Alice",
"middleName": undefined,
"age": 30
}
Error: 'undefined' is not a valid JSON value
✅ Correct
{
"name": "Alice",
"middleName": null,
"age": 30
}
// Or omit the property entirely:
{
"name": "Alice",
"age": 30
}
Use null or omit the property
Error 3.2: Functions and Special Objects
// These will be omitted or cause errors:
const invalid = {
func: function() { return 42; }, // Omitted
date: new Date(), // Becomes ISO string
regex: /test/g, // Becomes {}
symbol: Symbol('test'), // Omitted
undefined: undefined // Omitted
};
JSON.stringify(invalid);
// Result: {"date":"2025-01-16T10:30:00.000Z","regex":{}}
Solution: Custom Serialization
const data = {
func: function() { return 42; },
date: new Date('2025-01-16')
};
// Use replacer function
const json = JSON.stringify(data, (key, value) => {
if (typeof value === 'function') {
return value.toString();
}
if (value instanceof Date) {
return { __type: 'Date', value: value.toISOString() };
}
return value;
});
4. Circular Reference Errors
TypeError: Converting circular structure to JSON
const obj = { name: 'Alice' };
obj.self = obj; // Circular reference!
JSON.stringify(obj);
// TypeError: Converting circular structure to JSON
Solution: Detect and Handle Circular References
function safeStringify(obj, indent = 2) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular Reference]';
}
seen.add(value);
}
return value;
}, indent);
}
const obj = { name: 'Alice' };
obj.self = obj;
console.log(safeStringify(obj));
// Works! Circular ref replaced with "[Circular Reference]"
5. Encoding and Character Issues
Error 5.1: Invalid UTF-8 Characters
Problem: Special Characters Break Parsing
// JSON with non-ASCII characters
{"name": "Café", "emoji": "☕"}
// Solution: Ensure UTF-8 encoding
// In HTTP headers:
Content-Type: application/json; charset=utf-8
// In HTML meta tag:
Error 5.2: BOM (Byte Order Mark) Issues
// Some editors add BOM to files, causing parse errors
// \uFEFF{"name": "Alice"} ← BOM causes error
// Solution: Remove BOM before parsing
function removeBOM(str) {
return str.charCodeAt(0) === 0xFEFF ? str.slice(1) : str;
}
const jsonString = removeBOM(fileContent);
const data = JSON.parse(jsonString);
6. Number Precision Issues
Problem: Large Numbers Lose Precision
const bigNumber = 9007199254740993; // > Number.MAX_SAFE_INTEGER
const json = JSON.stringify({ id: bigNumber });
const parsed = JSON.parse(json);
console.log(parsed.id === bigNumber); // false!
console.log(parsed.id); // 9007199254740992 (wrong)
Solutions
// Solution 1: Use strings for large numbers
const data = {
id: "9007199254740993",
amount: "12345678901234567890"
};
// Solution 2: Use BigInt (Node.js/modern browsers)
const bigInt = 12345678901234567890n;
const json = JSON.stringify({ value: bigInt.toString() });
// Solution 3: Use libraries like json-bigint
const JSONbig = require('json-bigint');
const data = JSONbig.parse('{"id": 9007199254740993}');
console.log(data.id); // Preserves precision
7. API Response Errors
Error 7.1: HTML Response Instead of JSON
Common Scenario
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data));
// Error: Unexpected token < in JSON at position 0
// Cause: Server returned HTML error page instead of JSON
Robust Error Handling
async function fetchJSON(url) {
const response = await fetch(url);
// Check Content-Type header
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
throw new Error(`Expected JSON, got: ${text.slice(0, 100)}`);
}
// Check HTTP status
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
try {
return await response.json();
} catch (error) {
const text = await response.text();
throw new Error(`Invalid JSON: ${error.message}\nResponse: ${text.slice(0, 100)}`);
}
}
Error 7.2: Empty Response Body
// 204 No Content returns empty body
fetch('/api/delete/123')
.then(res => res.json()) // Error: Unexpected end of JSON input
// Solution: Check for empty responses
fetch('/api/delete/123')
.then(async (res) => {
if (res.status === 204) {
return null; // No content expected
}
return res.json();
});
8. Validation Errors
Schema Mismatch
Expected vs Actual Structure
// Expected:
{
"user": {
"id": 123,
"name": "Alice"
}
}
// Received:
{
"data": {
"user": {
"id": 123,
"name": "Alice"
}
}
}
// Error: Cannot read property 'id' of undefined
Defensive Coding
// Bad: Assumes structure
const userId = response.user.id;
// Good: Check at each level
const userId = response?.user?.id;
// Better: Validate with schema
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
user: {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' }
},
required: ['id', 'name']
}
},
required: ['user']
};
const validate = ajv.compile(schema);
if (!validate(response)) {
console.error('Invalid response:', validate.errors);
}
9. Debugging Tools and Techniques
Online JSON Validators
- JSON Utils Validator - Real-time validation with error highlighting
- JSONLint.com - Popular validator with error details
- JSONFormatter.org - Format and validate simultaneously
Browser DevTools
// View JSON responses in Network tab
// Chrome DevTools → Network → Select request → Response
// Copy as cURL to reproduce issues
// Right-click request → Copy → Copy as cURL
// Pretty-print in Console
console.log(JSON.stringify(data, null, 2));
Command Line Tools
# Validate JSON file
cat data.json | python -m json.tool
# Or with jq
cat data.json | jq .
# Find syntax errors
jq . data.json
# Shows line number of first error
Custom Debug Helper
function debugJSON(jsonString, context = '') {
console.log(`\n=== Debugging JSON: ${context} ===`);
console.log(`Length: ${jsonString.length} characters`);
console.log(`First 50 chars: ${jsonString.slice(0, 50)}`);
console.log(`Last 50 chars: ${jsonString.slice(-50)}`);
try {
const parsed = JSON.parse(jsonString);
console.log('✅ Valid JSON');
console.log('Type:', Array.isArray(parsed) ? 'Array' : typeof parsed);
console.log('Parsed:', parsed);
return parsed;
} catch (error) {
console.error('❌ Parse Error:', error.message);
// Find error position
const match = error.message.match(/position (\d+)/);
if (match) {
const pos = parseInt(match[1]);
const start = Math.max(0, pos - 50);
const end = Math.min(jsonString.length, pos + 50);
console.log(`\nNear error position ${pos}:`);
console.log(jsonString.slice(start, end));
console.log(' '.repeat(pos - start) + '^');
}
return null;
}
}
// Usage
const result = debugJSON(suspiciousJSON, 'API Response');
10. Prevention Best Practices
Checklist for Error-Free JSON
- ✅ Always use double quotes for keys and strings
- ✅ No trailing commas after last element
- ✅ Escape special characters (\", \\, \n, \t)
- ✅ Use null instead of undefined
- ✅ Validate before deployment with automated tests
- ✅ Use schema validation (JSON Schema, TypeScript)
- ✅ Handle API errors gracefully
- ✅ Check Content-Type headers
- ✅ Use try-catch blocks when parsing
- ✅ Test with edge cases (empty arrays, null values, special characters)
- ✅ Use linters (ESLint) to catch JSON issues early
- ✅ Enable strict mode in editors for JSON files
Quick Reference: Error Messages
Error: "Unexpected token"
→ Check for: Missing quotes, trailing commas, comments
Error: "Unexpected end of JSON input"
→ Check for: Incomplete JSON, missing brackets/braces
Error: "Converting circular structure to JSON"
→ Check for: Object referencing itself
Error: "Unexpected token < in JSON"
→ Check for: HTML response instead of JSON
Error: "Cannot read property 'X' of undefined"
→ Check for: Missing properties, wrong structure
Error: "Invalid or unexpected token"
→ Check for: Unescaped special characters, invalid data types
Conclusion
Most JSON errors fall into predictable categories with straightforward fixes. By understanding common mistakes, using validation tools, and implementing defensive coding practices, you can catch and fix JSON errors quickly. Remember: when in doubt, use a JSON validator to pinpoint exact issues before spending time debugging manually.
Debug Your JSON Instantly
Use our professional validation and formatting tools to catch errors fast.