JavaScript Reference ยท JSON, Errors and Reflection
JSON.stringify()
Reference for JavaScript JSON.stringify(): serialize values to JSON text, use replacer functions and arrays, pretty-print with indentation, and know what gets dropped.
JSON.stringify() converts a JavaScript value into a JSON string. Plain objects, arrays, strings, finite numbers, booleans and null convert as you would expect. Everything else follows rules that are worth knowing, because some values silently disappear or change.
The optional second argument filters or transforms values, and the third adds indentation for readable output.
JSON.stringify({ a: 1, b: [true, null] }); // '{"a":1,"b":[true,null]}'
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
JSON.stringify(value) JSON.stringify(value, replacer) JSON.stringify(value, replacer, space)
| Name | Description |
|---|---|
value |
The value to serialize. |
replacer |
Optional. A function (key, value) called for every property (the root has key ""), whose return value is serialized instead; or an array of strings and numbers listing the only property names to include (applies at every depth of objects). null means no replacer. |
space |
Optional. A number (1 to 10 spaces) or a string (its first 10 characters) used for indentation. Omitted, 0 or "" gives compact output. |
Return value: a string, or undefined when the value cannot be represented (undefined, a function or a symbol at the top level).
Exceptions: TypeError for circular structures and for BigInt values (unless you convert them in toJSON() or a replacer).
Usage notes
- Dropped in objects,
nullin arrays.undefined, functions and symbols are omitted from objects but becomenullinside arrays, so array positions are preserved. - Numbers.
NaN,Infinityand-Infinitybecomenull. - Wrapper and special objects.
DatehastoJSON()and gives an ISO string.Map,Set,RegExpand most class instances withouttoJSON()lose their contents; maps and sets become{}. Convert them first, for example with[...map]orObject.fromEntries(map). - Only own enumerable string keys are written, in the usual property order. Symbol keys and inherited properties are ignored.
toJSON()runs first. If a value has atoJSON()method, its result is what the replacer sees.- Replacer functions are called with
thisset to the containing object. Return the value unchanged to keep it,undefinedto drop it. - Pretty-printing:
JSON.stringify(x, null, 2)is the usual way to display data. Empty arrays and objects stay as[]and{}. - Lone surrogates are written as escape sequences, so the output is always valid Unicode text.
- Not a deep clone. Types are lost on the round trip. Use
structuredClone()to copy values. - Cycles need handling yourself, such as a replacer that tracks seen objects or by restructuring the data.
Browser support
JSON.stringify() works in every browser and runtime, including very old ones.