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
| Value | How stringify treats it |
|---|---|
undefined | Dropped (in objects); becomes null (in arrays) |
| Functions | Dropped (objects); null (arrays) |
| Symbols | Dropped |
| Dates | Serialised as their ISO string |
| Map / Set | Empty object {} unless you add toJSON |
| Circular reference | Throws 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,
);
A single digit.
Discussion
Loading…