Difficulty: Beginner
What is JSON? Explain JSON.parse() and JSON.stringify() with their common pitfalls.
JSON (JavaScript Object Notation) is a lightweight data interchange format. Despite the name, it is language-independent and used widely for API communication and configuration.
- JSON.stringify(): Converts a JavaScript object into a JSON string - JSON.parse(): Converts a JSON string back into a JavaScript object
Common pitfalls: 1. undefined, functions, and Symbols are omitted during stringify 2. NaN and Infinity become null 3. Date objects become strings (not converted back by parse) 4. Circular references throw an error 5. JSON.parse of invalid JSON throws SyntaxError
const user = { name: "Alice", age: 25, hobbies: ["coding", "reading"] };
// Stringify
const json = JSON.stringify(user);
console.log(json);
console.log(typeof json);
// Parse
const parsed = JSON.parse(json);
console.log(parsed.name);
// Pretty print with indentation
console.log(JSON.stringify(user, null, 2));
JSON.stringify converts to string, JSON.parse converts back. The third argument of stringify controls indentation.
const data = {
name: "Test",
fn: function() {},
undef: undefined,
nan: NaN,
inf: Infinity,
date: new Date("2024-01-01"),
};
console.log(JSON.stringify(data));
// Deep clone trick (with limitations)
const original = { a: 1, b: { c: 2 } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c = 99;
console.log(original.b.c); // still 2
console.log(clone.b.c); // 99
Functions, undefined, and Symbols are silently removed. NaN/Infinity become null. The parse+stringify trick creates a deep clone but loses special types.
JSON, Serialization, Parsing, Data Exchange