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) => newValue to transform or drop values (return undefined to 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. Date uses this to become an ISO string.
  • Drops undefined, functions and symbols in objects (they become null inside arrays).
  • NaN and Infinity become null.
  • Throws on circular references and on BigInt values.

JSON.parse(text, reviver?)

  • Throws a SyntaxError on invalid JSON, so wrap untrusted input in try/catch.
  • reviver: (key, value) => newValue, called bottom-up, perfect for turning date strings back into Date objects.

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 localStorage with JSON.stringify and read back with a guarded JSON.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};
7
8// 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 2
13);
14console.log(json);
15
16// Reviver: turn ISO strings back into Dates
17const 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 10
20
21// toJSON controls serialisation
22class 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"}
27
28// Safe parse
29const 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.

Open in study app