Skip to content
Plurafy

JSON and Data Serialization

Working with JSON data formats

Parse JSON from APIs, handle serialization of complex objects, and deal with edge cases like circular references.

JSON (JavaScript Object Notation) is the standard format for data exchange. JavaScript has built-in methods for parsing and stringifying JSON.

// Parse string to object
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // 'John'
// With arrays
const arrayJson = '[1, 2, 3, 4, 5]';
const numbers = JSON.parse(arrayJson);
// Error handling
try {
JSON.parse('{invalid json}');
} catch (e) {
console.error('Invalid JSON:', e.message);
}
const user = {
name: 'John',
age: 30,
email: 'john@example.com'
};
// Convert to string
const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"John","age":30,"email":"john@example.com"}'
// Pretty print
const formatted = JSON.stringify(user, null, 2);
console.log(formatted);
/* {
"name": "John",
"age": 30,
"email": "john@example.com"
} */
// Custom serialization with replacer
const 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 reviver
const 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); // true
// ❌ This throws an error
const circular = { name: 'John' };
circular.self = circular;
// JSON.stringify(circular); // TypeError: Converting circular structure
// ✅ Solution: Use replacer
const json = JSON.stringify(circular, (key, value) => {
if (typeof value === 'object' && value === circular) {
return '[Circular]';
}
return value;
});
// ✅ Solution: Use WeakSet
const 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;
});
// Cache stringified data
class 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 JSON
async 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
}
}