JavaScript JSON Serializer & Parser Playground
Deep dive into JSON.parse and JSON.stringify. Test custom revivers, replacers, safe parsing patterns, and generate production-ready Node.js file operations.
JSON.parse vs JSON.stringify in Modern JavaScript
JSON (JavaScript Object Notation) is the backbone of web APIs. While JSON.parse() and JSON.stringify() appear straightforward, mastering their advanced parameters (reviver callbacks, replacer arrays, indent spacing) is essential for avoiding production bugs.
1. Transforming Dates with a Reviver
Standard JSON does not define a native date type; dates are serialized as ISO 8601 strings. By supplying a reviver function to JSON.parse(), string timestamps are automatically reconstituted into real Date objects:
const data = JSON.parse(rawJson, (key, value) => {
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
});
2. Safe Parsing with Error Boundaries
Never call JSON.parse() directly on unvalidated network input without an error handler. An unexpected character will crash the thread:
function safeJsonParse(str, fallback = null) {
try {
return JSON.parse(str);
} catch (err) {
console.warn("JSON Parse Failed:", err.message);
return fallback;
}
}