Common JSON Mistakes and How to Avoid Them
JSON syntax errors can be frustrating to debug. Here are the most common mistakes developers make and how to avoid them in your projects.
1. Trailing Commas
One of the most common JSON errors is including a trailing comma after the last element in an array or object. While JavaScript allows this, JSON does not.
{
"name": "John",
"age": 30,
}{
"name": "John",
"age": 30
}2. Single Quotes Instead of Double Quotes
JSON requires double quotes for both keys and string values. Single quotes are not valid in JSON, even though they work in JavaScript objects.
{
'name': 'John',
'city': 'New York'
}{
"name": "John",
"city": "New York"
}3. Unquoted Keys
All keys in JSON must be quoted with double quotes. Unlike JavaScript object literals, JSON does not allow unquoted property names.
{
name: "John",
age: 30
}{
"name": "John",
"age": 30
}4. Comments in JSON
JSON does not support comments of any kind. Neither single-line (//) nor multi-line (/* */) comments are allowed. If you need comments, consider using JSON5 or a configuration format like YAML.
{
// User name
"name": "John",
/* User age */
"age": 30
}{
"name": "John",
"age": 30,
"_comment": "User info"
}5. Special Number Values
JSON does not support special number values like NaN, Infinity, or -Infinity. These will cause parsing errors.
{
"value": NaN,
"max": Infinity
}{
"value": null,
"max": 999999999
}6. Unescaped Special Characters
Certain characters must be escaped in JSON strings, including backslashes, quotes, and control characters like newlines and tabs.
{
"path": "C:\Users\name",
"quote": "He said "Hi""
}{
"path": "C:\\Users\\name",
"quote": "He said \"Hi\""
}Tips for Avoiding JSON Errors
- Use a JSON validator or formatter tool to check your JSON before using it
- Configure your code editor to highlight JSON syntax errors
- Use
JSON.stringify()to generate JSON from JavaScript objects - Enable strict mode in your JSON parser to catch errors early
- Consider using TypeScript or JSON Schema for type validation
Conclusion
While JSON is designed to be simple, these common mistakes can cause frustrating debugging sessions. By understanding these pitfalls and using proper tooling, you can avoid most JSON-related issues in your development workflow.