iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JSON Stringify

JSON.stringify turns a JavaScript value into a JSON text. The optional second and third arguments let you filter properties and pretty-print.

Signature

JS
JSON.stringify(value, replacer?, indent?);

Pretty-print

JS
JSON.stringify({ a: 1, b: 2 });             // '{"a":1,"b":2}'
JSON.stringify({ a: 1, b: 2 }, null, 2);    // 2-space indent
JSON.stringify({ a: 1, b: 2 }, null, "\t"); // tab indent

The replacer

JS
// Function replacer — runs for every (key, value)
JSON.stringify(user, (key, value) =>
  key === "password" ? undefined : value
);
// returning undefined drops the property

// Array replacer — allowlist of keys to keep
JSON.stringify(user, ["id", "name"]);     // '{"id":1,"name":"Ada"}'

toJSON hook

If a value has a toJSON() method, stringify uses its result instead.

JS
class Money {
  constructor(cents, currency = "USD") { this.cents = cents; this.currency = currency; }
  toJSON() { return { amount: this.cents / 100, currency: this.currency }; }
}

JSON.stringify(new Money(1599));
// '{"amount":15.99,"currency":"USD"}'

What gets dropped

ValueHow stringify treats it
undefinedDropped (in objects); becomes null (in arrays)
FunctionsDropped (objects); null (arrays)
SymbolsDropped
DatesSerialised as their ISO string
Map / SetEmpty object {} unless you add toJSON
Circular referenceThrows TypeError
Tip: Want a quick "deep clone" of plain data? structuredClone(value) handles dates, sets, maps, and circular references — things stringify drops or chokes on.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JSON Stringify!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Pretty-print with 2-space indent.

const text = JSON.stringify(obj, null, );

Test yourself

Q1. Pretty-print JSON with 2-space indent using…
Q2. `undefined` properties on an object become…
Q3. Cyclic references during stringify cause…

Discussion

Loading…