The Challenge of JSON Errors
JSON (JavaScript Object Notation) is deceptively simple. Its minimalist syntax makes it easy to read and write, yet that same simplicity leaves little room for error. A single misplaced comma or missing quote can render an entire JSON document invalid, triggering parsing failures that cascade through your application.
Understanding common JSON validation errors—and knowing how to fix them quickly—is essential for every developer working with web APIs, configuration files, or data interchange. This comprehensive guide explores the most frequent JSON errors encountered in real-world development and provides practical solutions for each.
1. Trailing Commas
The Error
Trailing commas are the most common JSON validation error. While JavaScript allows trailing commas in arrays and objects for developer convenience, the JSON specification explicitly prohibits them. This discrepancy trips up many developers transitioning between JavaScript and JSON.
Invalid:
{
"name": "John Doe",
"age": 30,
"city": "New York",
}
Error message: Unexpected token '}' at position 54
The Fix
Remove any comma after the last item in arrays or objects:
Valid:
{
"name": "John Doe",
"age": 30,
"city": "New York"
}
Prevention Tips
- Use a JSON validator or linter integrated into your code editor
- Enable automatic trailing comma removal in your formatter
- When copying from JavaScript, always validate before using as JSON
2. Single Quotes Instead of Double Quotes
The Error
JSON requires double quotes (") for all strings and property names. Single quotes (') are not valid in JSON, despite being acceptable in JavaScript. This is another frequent source of confusion for JavaScript developers.
Invalid:
{
'name': 'John Doe',
'active': true
}
Error message: Unexpected token ' at position 2
The Fix
Replace all single quotes with double quotes:
Valid:
{
"name": "John Doe",
"active": true
}
Why This Matters
This strict requirement ensures consistency across all JSON parsers and programming languages. While JavaScript is lenient about quote types, JSON's specification demands uniformity to maintain cross-platform compatibility.
3. Unquoted Property Names
The Error
All object keys (property names) must be enclosed in double quotes. This differs from JavaScript object literals, where quotes around property names are often optional.
Invalid:
{
name: "John Doe",
age: 30
}
Error message: Unexpected token 'n' at position 3
The Fix
Wrap all property names in double quotes:
Valid:
{
"name": "John Doe",
"age": 30
}
Common Scenario
This error frequently appears when developers copy JavaScript object literals directly into JSON configuration files or API payloads. Modern code editors with JSON mode can highlight unquoted keys as errors.
4. Missing Commas Between Elements
The Error
JSON requires commas to separate array elements and object properties. Forgetting a comma between elements prevents proper parsing.
Invalid:
{
"firstName": "John"
"lastName": "Doe"
}
Error message: Unexpected string at position 27
The Fix
Add commas between all elements (except the last one):
Valid:
{
"firstName": "John",
"lastName": "Doe"
}
Detection Strategy
When you see "Unexpected string" or "Unexpected token" errors pointing to a valid-looking line, check for a missing comma on the previous line. This pattern reveals most missing comma errors quickly.
5. Mismatched Brackets and Braces
The Error
Every opening bracket [ must have a corresponding closing bracket ], and every opening brace { must have a closing brace }. Mismatched pairs create parsing errors that can be difficult to diagnose in large JSON files.
Invalid:
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
},
"total": 2
Error message: Unexpected end of JSON input
The Fix
Ensure every opening bracket/brace has a matching closing bracket/brace:
Valid:
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
],
"total": 2
}
Debugging Technique
Use a JSON validator that shows line numbers and matching pairs. Many code editors provide bracket matching that highlights corresponding opening and closing brackets when you position your cursor on one. For complex nested structures, consider using a JSON formatter that visually indents nested levels.
6. Invalid Number Formats
The Error
JSON supports numbers but has strict formatting rules: no leading zeros (except for 0.x decimals), no hexadecimal notation, and no special values like NaN or Infinity.
Invalid:
{
"quantity": 007,
"price": 0xFF,
"discount": NaN
}
The Fix
Use standard decimal notation and null for invalid numbers:
Valid:
{
"quantity": 7,
"price": 255,
"discount": null
}
Special Cases
- Leading zeros:
007→7 - Hexadecimal:
0xFF→255 - Not a number:
NaN→null - Infinity:
Infinity→ Use a very large number or null - Scientific notation: Valid (
1.5e10is allowed)
7. Unsupported Data Types
The Error
JSON only supports six data types: string, number, boolean, null, array, and object. JavaScript features like functions, undefined values, dates, regular expressions, and comments are not valid in JSON.
Invalid:
{
"name": "John",
"age": undefined,
"callback": function() { return true; },
"created": new Date()
}
The Fix
Convert unsupported types to JSON-compatible equivalents:
Valid:
{
"name": "John",
"age": null,
"callback": null,
"created": "2025-01-30T10:30:00Z"
}
Conversion Guidelines
undefined→null- Functions → Remove or convert to string
- Dates → ISO 8601 string format
- RegExp → String representation
- Custom objects → Serialize with
toJSON()method
8. Comments in JSON
The Error
Despite JSON's JavaScript heritage, the JSON specification does not support comments. Many developers attempt to add comments for documentation, but parsers reject them.
Invalid:
{
// User information
"name": "John Doe",
/* Age in years */
"age": 30
}
Error message: Unexpected token '/' at position 3
The Fix
Remove all comments. For documentation, consider:
- Using a documentation field:
{
"_comment": "User information",
"name": "John Doe",
"age": 30
}
- Maintaining separate documentation files
- Using JSONC (JSON with Comments) for configuration files where supported
Alternative Formats
Some modern tools support JSONC (JSON with Comments) for configuration files. Popular examples include VS Code's settings.json and various build tools. However, standard JSON parsers will reject JSONC files, so use this format only where explicitly supported.
9. Invalid Escape Sequences
The Error
String values can contain escape sequences, but only specific sequences are valid: \", \\, \/, \b, \f, \n, \r, \t, and Unicode escapes \uXXXX.
Invalid:
{
"path": "C:\new\folder",
"message": "Line 1\xLine 2"
}
The Fix
Use valid escape sequences:
Valid:
{
"path": "C:\\new\\folder",
"message": "Line 1\nLine 2"
}
Common Escape Sequences
\"- Double quote\\- Backslash\/- Forward slash (optional)\n- Newline\t- Tab\r- Carriage return\uXXXX- Unicode character (e.g.,\u00A9for ©)
10. Duplicate Keys
The Error
While not always caught by parsers, duplicate property names within the same object create ambiguity and unpredictable behavior. Different parsers handle duplicates differently—some use the first value, others use the last, and some reject the JSON entirely.
Problematic:
{
"name": "John Doe",
"age": 30,
"name": "Jane Doe"
}
The Fix
Ensure all property names within an object are unique:
Valid:
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}
Why Duplicates Are Dangerous
Even when parsers accept duplicate keys, the resulting behavior is undefined by the JSON specification. In JavaScript, later values typically override earlier ones, but you cannot rely on this across all platforms and languages. Always use unique property names to ensure consistent parsing.
Debugging Strategies for Complex JSON Errors
When facing complex JSON errors in large files, use these systematic approaches:
1. Use a JSON Validator
Online JSON validators provide immediate feedback with line-specific error messages. Our JSON Validator tool highlights errors, shows exact positions, and suggests fixes—all processed securely in your browser.
2. Format First
Before debugging, format your JSON with proper indentation. Properly indented JSON makes structural errors like mismatched brackets immediately visible.
3. Binary Search Technique
For large files with unclear errors:
- Comment out (or remove) half the content
- Re-validate
- If valid, the error is in the removed half; otherwise, it's in the remaining half
- Repeat until you isolate the problematic section
4. Check Encoding
Ensure your JSON file uses UTF-8 encoding. Some characters in other encodings cause parsing failures. Hidden characters like byte order marks (BOM) can also trigger cryptic errors.
5. Validate Programmatically
Integrate JSON validation into your development workflow:
try {
const data = JSON.parse(jsonString);
console.log('Valid JSON:', data);
} catch (error) {
console.error('JSON Error:', error.message);
// Error message includes position information
}
Prevention: Best Practices
Prevent JSON errors before they happen:
- Use schema validation: Define JSON schemas and validate against them
- Automate formatting: Configure your editor to auto-format JSON on save
- Enable linting: Use ESLint with JSON plugins for real-time error detection
- Code reviews: Review JSON configuration changes like code
- Version control: Track JSON files in git to identify when errors were introduced
- Generate programmatically: Use libraries to generate JSON rather than writing it manually
- Test thoroughly: Validate JSON in automated tests before deployment
Conclusion
JSON validation errors are common but easily preventable with the right tools and awareness. The most frequent errors—trailing commas, incorrect quotes, and missing commas—can be caught immediately with proper validation tools integrated into your development environment.
By understanding these common pitfalls and implementing systematic debugging strategies, you can quickly identify and fix JSON errors before they impact production systems. Remember: a few seconds spent validating JSON saves hours of production debugging.
Need to validate your JSON right now? Try our free JSON Validator for instant error detection with detailed explanations—no server uploads, completely private and secure.