JavaScript · tutorial
JSON.stringify in JavaScript: replacer, space and escaped literals
How JSON.stringify works in JavaScript: replacer and space arguments, what gets dropped, circular references and double-stringify for an escaped literal.
Runs entirely in your browser — nothing you paste is uploaded
Everything runs in your browser. Nothing is sent anywhere.
How it works
The basics
JSON.stringify(value) returns a JSON string for any value it can represent. That is the whole API surface: a value, an optional replacer, and an optional space.
const user = { id: 7, name: 'Ada', admin: true };
JSON.stringify(user);
// '{"id":7,"name":"Ada","admin":true}'
The result is a string, not an object. Sending it to a server that expects a JSON body works; passing the object directly to fetch without a Content-Type header is the bug that follows.
Pretty printing with space
The third argument is a string (or a number of spaces, capped at 10) used for indentation:
JSON.stringify(user, null, 2);
This is for logs and for people reading a file. Do not send the pretty form over the wire — the whitespace is pure overhead, and some single-line protocols reject embedded newlines. There is no way to put a closing bracket or a comma style of your choice in; JSON.stringify always outputs JSON, never JavaScript.
The replacer argument
The second argument filters or transforms what comes out:
- An array of keys whitelists top-level properties:
JSON.stringify(user, ['id', 'name'])dropsadmin. - A function runs for every key, including nested ones, and its return value replaces the value. Returning
undefinedremoves the property.
JSON.stringify(user, (key, value) =>
key === 'password' ? undefined : value
);
Remember that the function is called on the root object too, with an empty key. That is why key === '' checks show up in real code.
The replacer is also the standard way to redact secrets before logging. Note that the filter runs top-down, so a value you remove is gone before its children are visited.
What gets dropped, and what becomes null
JSON.stringify does not throw on unrepresentable values inside objects — it silently removes them:
| Value | In an object | In an array |
|---|---|---|
undefined |
key removed | becomes null |
| function | key removed | becomes null |
Symbol |
key removed | becomes null |
NaN, Infinity |
becomes null |
becomes null |
Two special cases:
- A
Dateis serialised through itstoJSON()method, so you get an ISO 8601 string, not an object and not a timestamp number. - A
BigIntthrowsTypeError: Do not know how to serialize a BigInt. Convert it to a string first, or the whole request fails.
Circular references
const a = {}; a.self = a;
JSON.stringify(a); // TypeError: Converting circular structure to JSON
The fix is a WeakSet seen-list inside the replacer, or a library such as flatted for a JSON-safe format that keeps the loop. This is the error you see when you try to serialise an Express req, a DOM node, or any object graph with a parent pointer.
Getting an escaped string literal
JSON text is not a string literal. If you paste {"id":7} into a JavaScript or Java source file, the quotes end the string early. Two passes fix it:
JSON.stringify(JSON.stringify(user));
// '"{\"id\":7,\"name\":\"Ada\",\"admin\":true}"'
The inner call makes JSON text; the outer call escapes it and wraps it in quotes. JSON.parse twice goes back, one layer per call. If you would rather have this done in the browser, the JSON escape page has a two-tab converter for exactly this pair of directions.
Custom output with toJSON
If a value has a toJSON method, JSON.stringify calls it and serialises the result. That is how Date produces an ISO string, and it is the cleanest place to control how your own class leaves the process:
class Money {
constructor(cents) { this.cents = cents; }
toJSON() { return (this.cents / 100).toFixed(2); }
}
One caveat: toJSON runs before the replacer sees the value, so both hooks in the same object can surprise you.
Going back: JSON.parse, and the reviver
JSON.parse(text, reviver) is the reverse, and its second argument is the mirror of the replacer — handy for turning ISO dates back into Date objects. Two things it will not do: it will not resurrect dropped keys, and it will not restore 64-bit integers. A numeric ID such as 1234567890123456789 loses its last digits because JavaScript numbers are doubles; keep big IDs as strings on both sides.
A short checklist
JSON.stringify(undefined)returnsundefined, not'null'— the difference matters when you write it to a field.- Round-tripping strips formatting, key order and any property whose value is not representable.
- Throwing on getters: use
getaccessors only if you are happy with them running during serialisation. - Serialise once at the boundary. Most "JSON is broken" bugs are a payload serialised at two layers.
Try it
The converter at the top of this page runs the same operations in your browser: paste a value, get the JSON text, the escaped literal, or a JavaScript object literal with unquoted keys — depending on the tab. Nothing is uploaded. For the escape/unescape pair on its own, use JSON escape; for the plain text form, JSON to string.
FAQ
How does JSON.stringify work in JavaScript?
JSON.stringify(value) turns a value into a JSON string. Add a third argument for indentation — JSON.stringify(value, null, 2) — and use the second argument (replacer) when you need to filter keys or redact values before logging.
Why would I call JSON.stringify twice?
Use JSON.stringify(JSON.stringify(value)). The first call produces JSON text, the second escapes it and wraps it in quotes so it can be pasted into source code. JSON.parse twice reverses it.
Why do I get “Converting circular structure to JSON”?
Because the object contains a reference to itself, directly or through a chain. JSON has no way to express a loop, so it throws a TypeError. Track seen objects in a WeakSet inside the replacer, or serialise only the fields you need.
What does JSON.stringify drop without warning?
Properties whose value is undefined, a function or a symbol are removed from objects, and become null inside arrays. NaN and Infinity become null, and a BigInt throws instead of converting.
Can JSON.stringify produce a JavaScript object literal?
No. JSON.stringify outputs JSON: double-quoted keys, no trailing commas, no comments. For a JavaScript object literal you need a formatter that unquotes identifiers and switches to single quotes — the JSON → JS object tab on this site does that.