⚡ Lesson 21 of 30
JSON & Data Exchange
Parse and serialize JSON, handle edge cases, and work with complex nested data structures.
JSON Basics
JSON (JavaScript Object Notation) is the universal data exchange format. It uses double-quoted keys and supports strings, numbers, booleans, null, objects, and arrays:
const json = '{"name":"Alice","age":30,"hobbies":["JS","hiking"]}';
const obj = JSON.parse(json);
console.log(obj.name); // "Alice"
console.log(obj.hobbies[1]); // "hiking"
const backToJson = JSON.stringify(obj);
console.log(backToJson);
JSON.stringify Options
const data = { name:"Alice", score:95, password:"secret" };
// Pretty-print with 2-space indent
console.log(JSON.stringify(data, null, 2));
// Replacer — exclude sensitive fields
const safe = JSON.stringify(data, ["name","score"]);
console.log(safe); // {"name":"Alice","score":95}
Reviver Function
Transform values as they are parsed:
const raw = '{"created":"2026-01-15","amount":"1299.99"}';
const parsed = JSON.parse(raw, (key, value) => {
if (key === "created") return new Date(value);
if (key === "amount") return parseFloat(value);
return value;
});
console.log(parsed.created instanceof Date); // true
console.log(parsed.amount + 1); // 1300.99
Deep Clone with JSON
A quick (but imperfect) way to deep-copy plain objects:
const original = { a:1, b: { c: [1,2,3] } };
const clone = JSON.parse(JSON.stringify(original));
clone.b.c.push(4);
console.log(original.b.c); // [1,2,3] — unaffected
console.log(clone.b.c); // [1,2,3,4]
// Note: loses undefined, functions, Date objects, etc.
structuredClone (Modern)
The modern way to deep-clone — handles Date, Map, Set, etc.:
const obj = { date: new Date(), scores: new Map([["Alice",95]]) };
const clone = structuredClone(obj);
clone.date.setFullYear(2000);
console.log(obj.date.getFullYear()); // 2026 — unaffected