JSON (parse, stringify)
📖 Concept
JSON (JavaScript Object Notation) is a lightweight data format for storing and transferring data. It's the lingua franca of web APIs.
JSON.stringify(value, replacer, space) — Converts a JS value to a JSON string
JSON.parse(text, reviver) — Parses a JSON string back to a JS value
JSON supports: strings, numbers, booleans, null, objects, arrays JSON does NOT support: functions, undefined, Symbol, BigInt, Date (serialized as string), Map, Set, RegExp
🏠 Real-world analogy: JSON is like a packing list. You write down your items (stringify) to ship them. The receiver reads the list (parse) and reconstructs the items.
💻 Code Example
1// Basic usage2const user = { name: "Alice", age: 25, hobbies: ["coding", "reading"] };3const json = JSON.stringify(user);4// '{"name":"Alice","age":25,"hobbies":["coding","reading"]}'5const parsed = JSON.parse(json);67// Pretty printing8console.log(JSON.stringify(user, null, 2));910// Replacer function — filter/transform values11const filtered = JSON.stringify(user, (key, value) => {12 if (key === "age") return undefined; // Exclude age13 return value;14});15// '{"name":"Alice","hobbies":["coding","reading"]}'1617// Replacer array — whitelist keys18const partial = JSON.stringify(user, ["name", "age"]);19// '{"name":"Alice","age":25}'2021// Reviver function — transform during parsing22const jsonWithDate = '{"name":"Alice","joined":"2024-01-15T10:30:00.000Z"}';23const parsed2 = JSON.parse(jsonWithDate, (key, value) => {24 if (key === "joined") return new Date(value);25 return value;26});27console.log(parsed2.joined instanceof Date); // true2829// toJSON method — custom serialization30class User {31 constructor(name, password) {32 this.name = name;33 this.password = password;34 }35 toJSON() {36 return { name: this.name }; // Exclude password!37 }38}39console.log(JSON.stringify(new User("Alice", "secret")));40// '{"name":"Alice"}'4142// Deep clone trick (simple cases only)43const deepCopy = JSON.parse(JSON.stringify(user));
🏋️ Practice Exercise
Mini Exercise:
- Write a safe JSON parse function with error handling
- Implement a replacer that redacts sensitive fields (password, ssn, etc.)
- Write a reviver that converts ISO date strings back to Date objects
- Compare JSON deep clone vs structuredClone — test edge cases
⚠️ Common Mistakes
JSON.stringifyignoresundefined, functions, and Symbols — they disappear from the outputJSON.parse(JSON.stringify(obj))loses Date objects (become strings), undefined values, and functionsNot wrapping
JSON.parsein try/catch — invalid JSON throws SyntaxErrorJSON.stringifycan't handle circular references — throws TypeErrorJSON keys MUST be double-quoted strings — single quotes or unquoted keys are invalid JSON
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for JSON (parse, stringify). Login to unlock this feature.