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.
Emily Watson
• Technical Writer & Web DeveloperEmily is a web developer and technical writer with 6 years of experience covering JavaScript ecosystems, developer tooling, and data formats. She specialises in making complex technical concepts approachable for developers at all levels, with a particular focus on JSON fundamentals, formatting best practices, and the tools developers reach for every day.
The Complete Guide to Common JSON Errors and How to Fix Them
JSON syntax errors are the bane of every developer's existence. You copy an API response, paste it into your code, and suddenly everything breaks with cryptic error messages like "SyntaxError: Unexpected token" or "Unexpected end of JSON input." This comprehensive guide covers every common JSON error you'll encounter, shows you exactly how to fix them, and teaches you prevention strategies to avoid them in the first place.
Understanding JSON Error Messages
Before diving into specific errors, let's decode what JSON parsers are telling you when they fail:
"Unexpected token X": The parser found character X where it didn't expect it. Usually means missing comma, quote, or bracket. "Unexpected end of JSON input": The JSON ended prematurely—you're probably missing closing brackets or braces. "Expected property name or '}'": Inside an object, the parser expected either a property name in quotes or the closing brace. "Unexpected string": A string appeared where it shouldn't—usually means a missing comma before it.Most JSON errors fall into a handful of categories. Master these and you'll debug JSON errors in seconds instead of minutes.
Error #1: Missing or Extra Commas (The Most Common)
Comma errors account for approximately 40% of all JSON syntax errors. They're easy to make because JavaScript objects allow trailing commas, but JSON doesn't.
Missing Commas
Wrong:{
"name": "John"
"age": 30
}
Error Message: SyntaxError: Expected ',' or '}' after property value in JSON
Correct:
{
"name": "John",
"age": 30
}
Why This Happens: When manually typing or editing JSON, it's easy to forget the comma. When copying from JavaScript code, you might copy object literal syntax which doesn't require commas in some contexts.
Real-World Scenario:
// You copy this JavaScript object
const user = {
name: "John"
age: 30 // Oops, editor didn't catch missing comma
}
// Paste into JSON file → invalid JSON
Trailing Commas
Wrong:{
"name": "John",
"age": 30,
}
Error Message: SyntaxError: Trailing comma is not allowed in JSON
Correct:
{
"name": "John",
"age": 30
}
Why This Happens: Modern JavaScript, TypeScript, and many programming languages allow (and even encourage!) trailing commas for easier version control diffs. However, the JSON specification explicitly forbids them.
Real-World Scenario:
// Prettier or ESLint adds trailing commas to JavaScript
const config = {
apiKey: "abc123",
timeout: 5000, // ← trailing comma is valid in JS
};
// If you copy this to config.json → invalid JSON
Prevention: Use a JSON validator in your editor (ESLint with JSON plugins, or dedicated JSON validators) that highlights trailing commas immediately.
Error #2: Wrong Quote Characters (Single vs Double)
JSON is extremely strict about quotes: only double quotes (") are allowed. Single quotes (') and backticks (\) are invalid.
Single Quotes
Wrong:{
'name': 'John',
'age': 30
}
Error Message: SyntaxError: Unexpected token '
Correct:
{
"name": "John",
"age": 30
}
Why This Happens: JavaScript allows single quotes and backticks for strings, so developers accustomed to JS syntax naturally use them in JSON. Some programming languages (Python, PHP) prefer single quotes, making this error extremely common.
Real-World Scenario:
# Python code with single quotes
user_data = {
'name': 'John',
'email': 'john@example.com'
}
# Copy-paste to JSON → invalid
Quick Fix: Most text editors support regex find-replace:
- Find:
'([^'])'
Replace: "$1"
This converts all single-quoted strings to double-quoted in seconds.
Error #3: Unquoted Property Names
In JSON, all property names (keys) must be strings in double quotes. JavaScript object literals allow unquoted keys, but JSON doesn't.
Wrong:
{
name: "John",
age: 30,
isActive: true
}
Error Message: SyntaxError: Expected property name or '}' in JSON at position 2
Correct:
{
"name": "John",
"age": 30,
"isActive": true
}
Why This Happens: When you copy JavaScript object literal code (from console.log, examples, or your own code), the keys are often unquoted. JSON requires quotes even for simple alphanumeric keys.
Real-World Scenario:
// Browser DevTools shows objects without quotes
console.log({ name: "John", age: 30 });
// Console output: {name: "John", age: 30}
// If you copy this output → invalid JSON
Prevention: Use JSON.stringify() when copying data from browser consoles:
console.log(JSON.stringify({ name: "John", age: 30 }));
// Output: {"name":"John","age":30} → valid JSON
Error #4: Unescaped Special Characters
Strings containing quotes, backslashes, or newlines must properly escape these characters.
Unescaped Quotes
Wrong:
{
"message": "He said "Hello" and left"
}
Error Message: SyntaxError: Unexpected token H in JSON at position 24
Correct:
{
"message": "He said \"Hello\" and left"
}
Required Escape Sequences
| Character | Escape Sequence | Usage |
|-----------|----------------|--------|
|
" | \" | Double quote inside strings |
|
\\ | \\\\ | Backslash itself |
|
/ | \\/ | Forward slash (optional but recommended) |
| Newline |
\n | Line break |
| Tab |
\t | Tab character |
| Carriage return |
\r | CR (Windows line endings) |
| Backspace |
\b | Backspace character |
| Form feed |
\f | Form feed |
Real-World Example: File Paths
Wrong:
{
"path": "C:\Users\John\Documents"
}
Error: Backslashes aren't escaped, JSON parser sees \U as invalid escape sequence.
Correct:
{
"path": "C:\\Users\\John\\Documents"
}
Real-World Example: Multi-line Strings
Wrong:
{
"description": "First line
Second line
Third line"
}
Correct:
{
"description": "First line\nSecond line\nThird line"
}
Error #5: Invalid Values (undefined, NaN, Infinity)
JSON supports only six value types: string, number, boolean, null, object, and array. JavaScript types like
undefined, NaN, Infinity, functions, and symbols are not valid JSON.
Wrong:
{
"value": undefined,
"result": NaN,
"limit": Infinity,
"status": active
}
Correct:
{
"value": null,
"result": null,
"limit": null,
"status": "active"
}
Why This Happens: When using JSON.stringify() on JavaScript objects, undefined properties are silently omitted. But if you manually type or copy code, undefined might appear in your JSON.
Real-World Scenario:
const data = {
name: "John",
age: parseInt("not a number"), // NaN
status: undefined
};
console.log(data);
// {name: "John", age: NaN, status: undefined}
// If you copy this → invalid JSON
// Use JSON.stringify instead:
JSON.stringify(data);
// {"name":"John","age":null} → valid (undefined removed, NaN → null)
Rules for Values:
- Strings: Must use double quotes
- Numbers: Valid integers or floats (including negative, exponential notation)
- Booleans:
true or false (lowercase only)
Null: null (lowercase only)
Objects: {...}
Arrays: [...]
Error #6: Incorrect Boolean/Null Casing
JSON is case-sensitive.
true, false, and null must be lowercase.
Wrong:
{
"active": True,
"deleted": FALSE,
"data": NULL,
"empty": None
}
Error Message: SyntaxError: Unexpected token T in JSON
Correct:
{
"active": true,
"deleted": false,
"data": null,
"empty": null
}
Why This Happens: Python uses True, False, None (capitalized). C# uses True/False. When copying from these languages, the casing doesn't match JSON requirements.
Error #7: Mismatched Brackets and Braces
Every opening bracket must have a matching closing bracket. Nesting must be correct.
Wrong:
{
"users": [
{"name": "John"},
{"name": "Jane"}
}}
}
Error: Extra closing braces.
Wrong:
{
"users": [
{"name": "John"},
{"name": "Jane"}
}
Error: Missing closing bracket for array.
Correct:
{
"users": [
{"name": "John"},
{"name": "Jane"}
]
}
Debugging Technique: Use a code editor with bracket matching (VS Code, Sublime, etc.). Place cursor after any bracket and it highlights the matching bracket. If no highlight appears, you have a mismatch.
Advanced Technique: Count opening and closing brackets:
grep -o '{' file.json | wc -l # Count opening braces
grep -o '}' file.json | wc -l # Count closing braces
# Counts should match
Error #8: Comments in JSON (Not Allowed)
JSON does not support comments. No
//, / /, or # comments are allowed.
Wrong:
{
// User configuration
"name": "John",
/
This is the user's age /
"age": 30
}
Correct (Remove Comments):{
"name": "John",
"age": 30
}
Workaround: If you need comments, use a configuration format that supports them:
- JSONC (JSON with Comments): Supported by VS Code, TypeScript
- JSON5: Extended JSON with comments, trailing commas, and more
- YAML: Alternative format with native comment support
For production JSON, use separate documentation or README files for comments.
Error #9: Leading Zeros in Numbers
JSON doesn't allow leading zeros in numbers (except 0 itself and decimals like 0.5).
{
"code": 007,
"id": 00123
}
Correct:
{
"code": 7,
"id": 123
}
Or as strings if the leading zeros are significant:
{
"code": "007",
"id": "00123"
}
Debugging JSON Errors: Advanced Techniques
Use Online Validators
Tools like Big JSON Validator provide:
- Line and column numbers for errors
- Syntax highlighting
- Auto-fix for common errors
- Validation before deployment
Browser DevTools
When JSON parsing fails in browser JavaScript:
try {
JSON.parse(jsonString);
} catch (error) {
console.error('JSON Parse Error:', error.message);
console.error('Position:', error.message.match(/position (\d+)/)?.[1]);
}
CLI Validation
Use jq or python for quick command-line validation:
# Using jq
jq . file.json # If valid, prints formatted JSON
# Using Python
python -m json.tool file.json # Validates and formats
Editor Plugins
Install JSON validators in your editor:
- VS Code: JSON Validate
extension - Sublime Text: SublimeLinter-json
- Vim: vim-json
with ALE - IntelliJ: Built-in JSON validation
Prevention Strategies
1. Always Use JSON.stringify() in Code
// Wrong: manual string concatenation
const json = '{' + '"name":"' + name + '"}';
// Right: use JSON.stringify
const json = JSON.stringify({ name: name });
2. Validate Before Deployment
Add JSON validation to your CI/CD pipeline:
# GitHub Actions example
- name: Validate JSON files
run: |
find . -name "
.json" -exec python -m json.tool {} \; > /dev/null
3. Use Schema Validation
Define JSON Schema to validate structure, not just syntax:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["name", "age"],
"properties": {
"name": { "type": "string" },
"age": { "type": "number", "minimum": 0 }
}
}
4. Automated Formatting
Use Prettier to automatically format JSON on save:
// .prettierrc
{
"trailingComma": "none",
"tabWidth": 2
}
Quick Reference: Most Common Errors
after each property except the last , NaN with null or appropriate values, false, null, }, [, ] to ensure they matchConclusion
JSON errors are frustrating but predictable. Almost all JSON parsing failures fall into the eight categories covered in this guide. By mastering these patterns, you'll identify and fix JSON errors in seconds.
Key Takeaways:- Use JSON.stringify()` when generating JSON programmatically
- Validate JSON before deployment with online tools or CLI validation
- Enable JSON linting in your code editor
- Remember: JSON is stricter than JavaScript object syntax
- When debugging, check commas first (40% of errors), then quotes (30%), then brackets (20%)
Keep a JSON validator bookmarked and use it liberally. Your future self will thank you when you catch an error before it reaches production.
Related Articles
What is JSON? Complete Guide for Beginners 2026
Learn what JSON is, its syntax, data types, and use cases. A comprehensive beginner-friendly guide to understanding JavaScript Object Notation.
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.
Best JSON Online Tools 2026: Viewers, Validators, and Formatters
Comprehensive guide to the best JSON online tools. Compare viewers, validators, formatters, and converters for working with JSON data.