You paste JSON into your code. Everything looks fine. Then: SyntaxError: Unexpected token
Here are the 10 most common JSON mistakes I see (and how to fix them in seconds)."
Mistake #1: Trailing Commas
json// ❌ Wrong
{
"name": "John",
"age": 25, ← trailing comma breaks JSON
}
// ✅ Correct
{
"name": "John",
"age": 25
}
Why it breaks: JSON spec doesn't allow trailing commas
How to fix: Remove the last comma
Pro tip: Use a JSON validator to catch this
Mistake #2: Single Quotes Instead of Double Quotes
json// ❌ Wrong
{'name': 'John'}
// ✅ Correct
{"name": "John"}
Mistake #3: Comments in JSON
json// ❌ Wrong
{
// This is a user object
"name": "John"
}
// ✅ Correct (JSON doesn't support comments)
{
"_comment": "This is a user object",
"name": "John"
}
Mistake #4: Unquoted Keys
json// ❌ Wrong
{name: "John"}
// ✅ Correct
{"name": "John"}
Mistake #5: Using undefined or NaN
json// ❌ Wrong
{"age": undefined, "score": NaN}
// ✅ Correct
{"age": null, "score": null}
Mistake #6: Multi-line Strings Without Escaping
json// ❌ Wrong
{
"bio": "This is a
multi-line string"
}
// ✅ Correct
{
"bio": "This is a\nmulti-line string"
}
Mistake #7: Mixing Data Types Inconsistently
json// ❌ Confusing
{
"users": [
{"id": 1, "name": "John"},
{"id": "2", "name": "Jane"} ← ID is string here
]
}
// ✅ Consistent
{
"users": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"}
]
}
Mistake #8: Circular References
javascript// ❌ This crashes
const obj = {};
obj.self = obj;
JSON.stringify(obj); // Error!
// ✅ Avoid circular references
const obj = { name: "John" };
JSON.stringify(obj); // Works
Mistake #9: Special Characters Without Escaping
json// ❌ Wrong
{"path": "C:\Users\John"}
// ✅ Correct
{"path": "C:\\Users\\John"}
Mistake #10: Wrong MIME Type in API Responses
javascript// ❌ Wrong
res.setHeader('Content-Type', 'text/plain');
res.send(JSON.stringify(data));
// ✅ Correct
res.setHeader('Content-Type', 'application/json');
res.json(data);
How to Avoid These Mistakes
1. Use a JSON validator
Before using JSON, validate it. Tools like [jsontoall.tools/json-validator] catch these errors instantly.
2. Use JSON.parse() in try-catch
javascripttry {
const data = JSON.parse(jsonString);
} catch (e) {
console.error('Invalid JSON:', e.message);
}
3. Use a linter
ESLint can catch JSON issues in your code.
4. Test with sample data
Always test your JSON with edge cases.
Conclusion
"These 10 mistakes account for 90% of JSON errors I see. Bookmark this guide - you'll need it.
Need to validate JSON quickly? Try [jsontoall.tools] - instant validation, clear error messages, free."
Top comments (0)