stringify
Serializes a value to JSON text — pretty-printed with 2 spaces by default, or canonical.
Formatting:
- default — indented with 2 spaces, like a hand-written config file
{ indent: n }— indented withnspaces (an integer from 0 to 10);{ indent: 0 }gives a compact single line, the same asJSON.stringify(value)'canonical'— canonical JSON (RFC 8785, JSON Canonicalization Scheme): object keys sorted by UTF-16 code units, no whitespace at all, numbers in their shortest ECMAScript form. Two equal values always give the same bytes, so the output can be hashed, signed or compared. Canonical output can’t be indented — the RFC fixes every byte.
Same as JSON.stringify: toJSON() is called (a Date becomes its ISO string),
undefined, functions and symbols are dropped from objects and become null in arrays, and
Number/String/Boolean objects are unwrapped. Outside 'canonical', NaN and ±Infinity
silently become null, as there.
Throws instead of returning undefined or dropping data silently:
- a
TypeErrorwhenvalueitself isundefined, a function or a symbol - a
TypeErroron a circular structure or aBigInt(likeJSON.stringify) - with
'canonical', aRangeErroronNaN,±Infinityor a string with a lone surrogate, which canonical JSON can’t hold - a
RangeErrorwhenindentisn’t an integer from 0 to 10
The output is strict JSON, so it is also valid JSONC and JSON5.
Available since v3.1.3
Import
Section titled “Import”Signature
Section titled “Signature”Parameters
Section titled “Parameters”| Parameter | Type | Description |
|---|---|---|
value | unknown | The value to serialize |
formatting | StringifyFormatting | `{ indent }` (default `{ indent: 2 }`) or `‘canonical’` — see StringifyFormatting |
Returns
Section titled “Returns”string — The JSON text
Examples
Section titled “Examples”Pretty-print by default
Section titled “Pretty-print by default”Indented with 2 spaces, like a hand-written config file.
Compact output
Section titled “Compact output”indent: 0 gives a single line, like JSON.stringify(value).
Canonical JSON (RFC 8785)
Section titled “Canonical JSON (RFC 8785)”Sorted keys and no whitespace: equal values always give the same bytes, ready to hash or sign.
Related Types
Section titled “Related Types”StringifyFormatting
Section titled “StringifyFormatting”How stringify lays out its output:
{ indent }— pretty-printed withindentspaces per level (0for a compact single line)'canonical'— canonical JSON (RFC 8785), byte-for-byte reproducible
