Common JSON Mistakes
You'll learn the most common pitfalls developers encounter when working with JSON, and how to avoid them.
JSON has strict rules that differ from JavaScript object syntax, and violating them causes errors or unexpected behavior. Here are the mistakes to watch for:
Using Single Quotes
JSON requires double quotes for both keys and string values. Single quotes cause parsing errors:
// ❌ Invalid JSON - single quotes
const bad = "{'name': 'Alice'}";
JSON.parse(bad); // SyntaxError
// ✅ Valid JSON - double quotes
const good = '{"name": "Alice"}';
JSON.parse(good); // Works!
Trailing Commas
JavaScript allows trailing commas in objects, but JSON does not:
// ❌ Invalid JSON - trailing comma
const bad = '{"name": "Bob", "age": 30,}';
JSON.parse(bad); // SyntaxError
// ✅ Valid JSON - no trailing comma
const good = '{"name": "Bob", "age": 30}';
JSON.parse(good); // Works!
Date Objects Don't Serialize Properly
Dates become strings during serialization, losing their object type:
const obj = { created: new Date() };
const json = JSON.stringify(obj);
// json is '{"created":"2024-01-15T10:30:00.000Z"}'
const parsed = JSON.parse(json);
console.log(parsed.created instanceof Date); // false - it's a string!
Not All JavaScript Objects Are JSON-Safe
Functions, undefined, and Symbol values are either omitted or converted to null:
const obj = {
name: "Alice",
greet: function() { return "Hi"; },
secret: undefined
};
console.log(JSON.stringify(obj));
// '{"name":"Alice"}' - function and undefined are gone!
Key Takeaway: JSON is stricter than JavaScript — always use double quotes, avoid trailing commas, remember that Dates serialize to strings, and know that functions and undefined don't survive serialization.