The JavaScript JSON.stringify() method
The JSON.stringify() method converts a JavaScript value into a JSON string. JSON.stringify({a: 1}) gives '{"a":1}'. You use it to send data to a server or save it in localStorage. Pass a third argument to pretty-print: JSON.stringify(obj, null, 2). Its inverse is JSON.parse().
Overview
JSON.stringify() turns a JavaScript object, array or value into a JSON-formatted string. This is how data leaves your program: you stringify it to send in a fetch() request body, to store in localStorage (which only holds strings), or to log a clean snapshot of an object.
The third argument controls formatting. JSON.stringify(obj, null, 2) pretty-prints with two-space indentation, which makes logs and files human-readable. The second argument, a replacer, can filter or transform which properties get included — pass an array of key names to keep only those.
A few things quietly get dropped or changed, and it's worth knowing them: undefined, functions and symbols are omitted from objects (and become null in arrays), and Date objects turn into ISO strings. It also throws on circular references. Round-tripping through JSON.stringify() then JSON.parse() is a common (shallow-safe) way to deep-copy plain data.
Syntax
const json = JSON.stringify(value)
const json = JSON.stringify(value, replacer, space)
JSON.stringify({ a: 1 }) // '{"a":1}'
JSON.stringify(obj, null, 2) // pretty-printed
Parameters
The JSON.stringify() method accepts the following parameters.
| Parameter | Description |
|---|---|
value |
The JavaScript value (object, array, etc.) to convert to a JSON string. |
replacer |
Optional. A function to transform values, or an array of key names to keep. Use null to include everything. |
space |
Optional. Indentation for pretty-printing — a number of spaces (e.g. 2) or a string. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const user = { name: 'Ada', roles: ['admin', 'editor'] };
const compact = JSON.stringify(user);
const pretty = JSON.stringify(user, null, 2);
document.getElementById('out').textContent =
compact + '\n\n' + pretty;
</script>
Best practices
- Pretty-print for humans with
JSON.stringify(obj, null, 2). - Always pair it with JSON.parse() when round-tripping data.
- Remember
undefined, functions and symbols are dropped, and dates become strings. - Wrap it in
try/catchfor data that might contain circular references, which throw.
Frequently asked questions
What does JSON.stringify() do?
How do I pretty-print JSON in JavaScript?
JSON.stringify(obj, null, 2) indents with two spaces.Why are some properties missing from the JSON?
undefined, functions and symbols are dropped from objects. Dates are converted to ISO strings.How do I deep-copy an object with JSON?
JSON.parse(JSON.stringify(obj)) for plain data — but note it loses functions, dates and undefined. structuredClone() handles those cases properly.