How to Fix JSON Format Errors
A detailed guide to common JSON format errors, troubleshooting methods, and fix techniques with real-world examples and tool recommendations.
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format. It's based on JavaScript object syntax but is language-independent.
Basic JSON rules:
- Keys must be wrapped in double quotes
- Strings must use double quotes (not single quotes)
- No trailing comma after the last property
- Comments are not supported
- Only specific data types are allowed
Common JSON Error Types
1. Trailing Comma
Incorrect example:
{
"name": "Alice",
"age": 30,
}
Error message: Unexpected token } in JSON at position 29
Cause: The JSON specification doesn't allow a comma after the last property.
Fix:
{
"name": "Alice",
"age": 30
}
2. Using Single Quotes
Incorrect example:
{
'name': 'Alice',
'age': 30
}
Error message: Unexpected token ' in JSON at position 4
Cause: JSON strictly requires double quotes.
Fix:
{
"name": "Alice",
"age": 30
}
3. Unquoted Keys
Incorrect example:
{
name: "Alice",
age: 30
}
Error message: Unexpected token n in JSON at position 4
Cause: JSON keys must be strings, wrapped in double quotes.
Fix:
{
"name": "Alice",
"age": 30
}
4. Including Comments
Incorrect example:
{
// This is user info
"name": "Alice",
"age": 30 /* age */
}
Error message: Unexpected token / in JSON at position 6
Cause: The JSON specification doesn't support any form of comments.
Fix:
Remove all comments:
{
"name": "Alice",
"age": 30
}
5. Using Illegal Values
Incorrect example:
{
"value": undefined,
"num": NaN,
"func": function() {}
}
Error message: Unexpected token u in JSON at position 13
Cause: JSON only supports these value types:
- Strings
- Numbers
- Booleans (true/false)
- null
- Objects
- Arrays
It doesn't support undefined, NaN, Infinity, functions, etc.
Fix:
{
"value": null,
"num": null,
"note": "function not supported in JSON"
}
6. Multiple Top-Level Objects
Incorrect example:
{"name": "Alice"}
{"name": "Bob"}
Error message: Unexpected token { in JSON at position 20
Cause: JSON can only have one top-level value.
Fix:
Wrap in an array:
[
{"name": "Alice"},
{"name": "Bob"}
]
How to Troubleshoot JSON Errors
Method 1: Use Online Validation Tools
We recommend DevKit JSON Formatter:
- Paste your JSON
- The tool automatically detects error locations
- Provides formatted, correct JSON
Method 2: Validate with Code
JavaScript:
function validateJSON(jsonString) {
try {
JSON.parse(jsonString);
console.log("✅ Valid JSON");
return true;
} catch (e) {
console.error("❌ Invalid JSON:", e.message);
return false;
}
}
validateJSON('{"name": "Alice"}'); // ✅
validateJSON("{'name': 'Alice'}"); // ❌
Python:
import json
def validate_json(json_string):
try:
json.loads(json_string)
print("✅ Valid JSON")
return True
except json.JSONDecodeError as e:
print(f"❌ Invalid JSON: {e}")
return False
validate_json('{"name": "Alice"}') # ✅
validate_json("{'name': 'Alice'}") # ❌
Node.js (with detailed error location):
function parseJSONWithLocation(jsonString) {
try {
return JSON.parse(jsonString);
} catch (e) {
const match = e.message.match(/position (\d+)/);
if (match) {
const pos = parseInt(match[1]);
const lines = jsonString.substring(0, pos).split('\n');
const line = lines.length;
const column = lines[lines.length - 1].length + 1;
console.error(`Error location: Line ${line}, Column ${column}`);
}
throw e;
}
}
Method 3: Use an Editor
Editors like VS Code have built-in JSON validation:
- Save the file with a
.jsonextension - The editor will automatically mark syntax errors
- Hover to see error details
Best Practices for Preventing JSON Errors
1. Use JSON5 or JSONC (Development Environment)
If you need comments and more relaxed syntax, consider:
JSON5 (supports comments, single quotes, trailing commas):
{
// User info
'name': 'Alice',
'age': 30,
}
JSONC (JSON with Comments, common in VS Code configs):
{
// Compiler options
"compilerOptions": {
"target": "ES2020",
}
}
Note: These formats must be converted to standard JSON before being accepted by APIs.
2. Use Schema Validation
Define JSON Schema to validate data structure:
const Ajv = require("ajv");
const ajv = new Ajv();
const schema = {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number", minimum: 0 }
},
required: ["name", "age"]
};
const validate = ajv.compile(schema);
const data = { name: "Alice", age: 30 };
console.log(validate(data)); // true
const invalidData = { name: "Alice" };
console.log(validate(invalidData)); // false
console.log(validate.errors); // Detailed error info
3. Handle Special Values During Serialization
function safeStringify(obj) {
return JSON.stringify(obj, (key, value) => {
// Handle special values
if (value === undefined) return null;
if (typeof value === 'function') return null;
if (typeof value === 'number' && isNaN(value)) return null;
if (typeof value === 'number' && !isFinite(value)) return null;
return value;
});
}
const data = {
name: "Alice",
callback: function() {},
value: undefined,
num: NaN
};
console.log(safeStringify(data));
// {"name":"Alice","callback":null,"value":null,"num":null}
4. Use TypeScript Type Checking
interface User {
name: string;
age: number;
email?: string;
}
function parseUser(json: string): User | null {
try {
const data = JSON.parse(json);
// Runtime validation
if (typeof data.name !== 'string') throw new Error('Invalid name');
if (typeof data.age !== 'number') throw new Error('Invalid age');
return data as User;
} catch (e) {
console.error('Parse error:', e);
return null;
}
}
Frequently Asked Questions
What's the Difference Between JSON and JavaScript Objects?
| Feature | JSON | JavaScript Object |
|---|---|---|
| Format | Plain text | In-memory data structure |
| Keys | Must be double-quoted | Can be unquoted or single-quoted |
| Values | Limited types | Any type (including functions) |
| Comments | Not supported | Supported (in JS code) |
| Trailing commas | Not allowed | Allowed (ES5+) |
Why Doesn't JSON Support Comments?
JSON's design goal is simplicity and cross-platform compatibility. Comments would increase parser complexity, and comment syntax differs across languages.
If you need comments, you can:
- Use a dedicated field:
"_comment": "This is a note" - Use JSON5 or JSONC
- Document in external files
How to Handle JSON Errors in Large Files?
For large JSON files (> 10MB), we recommend:
- Stream parsing: Use libraries like
stream-json - Chunk validation: Validate file structure first
- Use professional tools: Like the
jqcommand-line tool
# Validate with jq
cat large.json | jq . > /dev/null
Summary
JSON errors are typically caused by:
- ❌ Trailing commas
- ❌ Single quotes (should use double quotes)
- ❌ Unquoted keys
- ❌ Comments
- ❌ Illegal values (undefined, NaN, functions)
- ❌ Multiple top-level objects
Solutions:
- Use online validation tools to quickly locate errors
- Use code for programmatic validation
- Follow JSON specifications and best practices
- Use Schema to validate data structure
Use DevKit JSON Formatter to quickly format and validate JSON data, automatically detect errors, and provide fix suggestions.