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

codeTap to expand ⛶
1// Basic usage
2const 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);
6
7// Pretty printing
8console.log(JSON.stringify(user, null, 2));
9
10// Replacer function — filter/transform values
11const filtered = JSON.stringify(user, (key, value) => {
12 if (key === "age") return undefined; // Exclude age
13 return value;
14});
15// '{"name":"Alice","hobbies":["coding","reading"]}'
16
17// Replacer array — whitelist keys
18const partial = JSON.stringify(user, ["name", "age"]);
19// '{"name":"Alice","age":25}'
20
21// Reviver function — transform during parsing
22const 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); // true
28
29// toJSON method — custom serialization
30class 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"}'
41
42// Deep clone trick (simple cases only)
43const deepCopy = JSON.parse(JSON.stringify(user));

🏋️ Practice Exercise

Mini Exercise:

  1. Write a safe JSON parse function with error handling
  2. Implement a replacer that redacts sensitive fields (password, ssn, etc.)
  3. Write a reviver that converts ISO date strings back to Date objects
  4. Compare JSON deep clone vs structuredClone — test edge cases

⚠️ Common Mistakes

  • JSON.stringify ignores undefined, functions, and Symbols — they disappear from the output

  • JSON.parse(JSON.stringify(obj)) loses Date objects (become strings), undefined values, and functions

  • Not wrapping JSON.parse in try/catch — invalid JSON throws SyntaxError

  • JSON.stringify can't handle circular references — throws TypeError

  • JSON 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.