JavaScriptMedium
What is JSON.parse() and JSON.stringify()?
JSON.stringify(value) converts a JavaScript value into a JSON string, and JSON.parse(text) converts a JSON string back into a value; both accept an optional function to customise the conversion.
JSON.stringify(value, replacer?, space?)
replacer: a function(key, value) => newValueto transform or drop values (returnundefinedto drop), or an array of keys to include.space: indentation for readable output, e.g.2.- Objects can define
toJSON()to control how they are serialised.Dateuses this to become an ISO string. - Drops
undefined, functions and symbols in objects (they becomenullinside arrays). NaNandInfinitybecomenull.- Throws on circular references and on
BigIntvalues.
JSON.parse(text, reviver?)
- Throws a
SyntaxErroron invalid JSON, so wrap untrusted input intry/catch. reviver:(key, value) => newValue, called bottom-up, perfect for turning date strings back intoDateobjects.
Deep cloning with JSON
JSON.parse(JSON.stringify(obj)) used to be the go-to deep clone, but it loses dates, undefined, Map, Set and fails on cycles. Prefer structuredClone(obj), which is built in everywhere now.
Practical tips
- Persist to
localStoragewithJSON.stringifyand read back with a guardedJSON.parse. - Use the replacer to strip secrets (passwords, tokens) before logging.
Code example
js
1const order = {2 id: 7,3 createdAt: new Date("2025-06-01T10:00:00Z"),4 password: "secret",5 amount: 10n,6};78// Replacer: drop secrets, convert BigInt (which would otherwise throw)9const json = JSON.stringify(10 order,11 (key, value) => (key === "password" ? undefined : typeof value === "bigint" ? value.toString() : value),12 213);14console.log(json);1516// Reviver: turn ISO strings back into Dates17const isoDate = /^\d{4}-\d{2}-\d{2}T/;18const parsed = JSON.parse(json, (key, value) => (typeof value === "string" && isoDate.test(value) ? new Date(value) : value));19console.log(parsed.createdAt instanceof Date, parsed.createdAt.getUTCHours()); // true 102021// toJSON controls serialisation22class Money {23 constructor(cents) { this.cents = cents; }24 toJSON() { return `$${(this.cents / 100).toFixed(2)}`; }25}26console.log(JSON.stringify({ price: new Money(1999) })); // {"price":"$19.99"}2728// Safe parse29const safeParse = (text, fallback = null) => {30 try { return JSON.parse(text); } catch { return fallback; }31};32console.log(safeParse("{bad json}", {})); // {}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.