JSON and Data Serialization
Working with JSON data formats
Challenge
Section titled “Challenge”Parse JSON from APIs, handle serialization of complex objects, and deal with edge cases like circular references.
Explanation
Section titled “Explanation”JSON (JavaScript Object Notation) is the standard format for data exchange. JavaScript has built-in methods for parsing and stringifying JSON.
Parsing JSON
Section titled “Parsing JSON”// Parse string to objectconst jsonString = '{"name": "John", "age": 30}';const obj = JSON.parse(jsonString);console.log(obj.name); // 'John'
// With arraysconst arrayJson = '[1, 2, 3, 4, 5]';const numbers = JSON.parse(arrayJson);
// Error handlingtry { JSON.parse('{invalid json}');} catch (e) { console.error('Invalid JSON:', e.message);}Stringify to JSON
Section titled “Stringify to JSON”const user = { name: 'John', age: 30, email: 'john@example.com'};
// Convert to stringconst jsonString = JSON.stringify(user);console.log(jsonString);// '{"name":"John","age":30,"email":"john@example.com"}'
// Pretty printconst formatted = JSON.stringify(user, null, 2);console.log(formatted);/* { "name": "John", "age": 30, "email": "john@example.com"} */Replacer and Reviver
Section titled “Replacer and Reviver”// Custom serialization with replacerconst data = { name: 'John', password: 'secret123', age: 30};
const json = JSON.stringify(data, (key, value) => { if (key === 'password') return undefined; // Exclude passwords return value;});
// Custom deserialization with reviverconst dateJson = '{"name":"John","created":"2024-01-15T10:30:00Z"}';const parsed = JSON.parse(dateJson, (key, value) => { if (key === 'created') return new Date(value); return value;});
console.log(parsed.created instanceof Date); // trueHandling Circular References
Section titled “Handling Circular References”// ❌ This throws an errorconst circular = { name: 'John' };circular.self = circular;// JSON.stringify(circular); // TypeError: Converting circular structure
// ✅ Solution: Use replacerconst json = JSON.stringify(circular, (key, value) => { if (typeof value === 'object' && value === circular) { return '[Circular]'; } return value;});
// ✅ Solution: Use WeakSetconst seen = new WeakSet();const json2 = JSON.stringify(circular, (key, value) => { if (typeof value === 'object' && value !== null) { if (seen.has(value)) return '[Circular]'; seen.add(value); } return value;});Performance Tips
Section titled “Performance Tips”// Cache stringified dataclass DataCache { constructor() { this.cache = new Map(); }
set(key, value) { this.cache.set(key, JSON.stringify(value)); }
get(key) { const json = this.cache.get(key); return json ? JSON.parse(json) : null; }}
// Streaming large JSONasync function parseJSONStream(response) { const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = '';
while (true) { const { done, value } = await reader.read(); if (done) break;
buffer += decoder.decode(value, { stream: true }); // Parse chunks }}