JSON.stringify()
JSON.stringify() does the opposite of JSON.parse(): it turns a JavaScript value into a JSON string. You use it to send data to a server, save it to a file or storage, or log it in a readable form.
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)Basic use
const user = { id: 5, name: "Khoa", admin: false, tags: ["beta"], manager: null };
const text = JSON.stringify(user);
console.log(text);
console.log(typeof text, text.length);{"id":5,"name":"Khoa","admin":false,"tags":["beta"],"manager":null}
string 67
Keys are quoted, strings use double quotes, and there is no extra whitespace.
How JavaScript values are converted
Not every JavaScript value has a JSON equivalent. stringify follows these rules:
| JavaScript value | In an object | In an array | On its own |
|---|---|---|---|
undefined, function, Symbol |
key is left out | becomes null |
returns undefined |
NaN, Infinity |
null |
null |
"null" |
Date |
ISO string (via toJSON()) |
ISO string | ISO string |
Map, Set |
{} |
{} |
"{}" |
BigInt |
TypeError | TypeError | TypeError |
const tricky = {
missing: undefined,
fn() { return 1; },
nan: NaN,
inf: Infinity,
when: new Date(Date.UTC(2025, 0, 15, 8, 30)),
set: new Set([1, 2]),
list: [undefined, () => 1, 3],
};
console.log(JSON.stringify(tricky));
console.log(JSON.stringify(undefined));
try {
JSON.stringify({ big: 10n });
} catch (err) {
console.log(err.name + ": " + err.message);
}{"nan":null,"inf":null,"when":"2025-01-15T08:30:00.000Z","set":{},"list":[null,null,3]}
undefined
TypeError: Do not know how to serialize a BigInt
Tip: To store a
SetorMap, convert it first:[...mySet]orObject.fromEntries(myMap).
The replacer
The second argument controls what gets included.
An array of keys acts as an allow-list:
const account = { id: 9, email: "an@example.com", password: "hunter2", plan: "pro" };
console.log(JSON.stringify(account, ["id", "plan"]));{"id":9,"plan":"pro"}
A function is called for every key/value pair, like a reviver in reverse. Return the value to keep it, a different value to change it, or undefined to drop it:
const account = { id: 9, email: "an@example.com", password: "hunter2", balance: 1234.5678 };
const json = JSON.stringify(account, (key, value) => {
if (key === "password") return undefined; // hide secrets
if (typeof value === "number" && !Number.isInteger(value)) {
return Math.round(value * 100) / 100; // 2 decimals
}
return value;
});
console.log(json);{"id":9,"email":"an@example.com","balance":1234.57}
The space argument: pretty printing
The third argument adds indentation. A number means that many spaces (up to 10); a string is used as the indent itself:
const point = { x: 1, y: [2, 3] };
console.log(JSON.stringify(point, null, 2));
console.log(JSON.stringify(point, null, "--"));{
"x": 1,
"y": [
2,
3
]
}
{
--"x": 1,
--"y": [
----2,
----3
--]
}
Pass null as the replacer when you only want indentation.
Custom output with toJSON()
If an object has a toJSON() method, stringify calls it and serializes whatever it returns. That's exactly how Date objects become strings:
class Money {
constructor(amount, currency) {
this.amount = amount;
this.currency = currency;
}
toJSON() {
return `${this.amount.toFixed(2)} ${this.currency}`;
}
}
const invoice = { id: "INV-7", total: new Money(49.5, "USD") };
console.log(JSON.stringify(invoice));{"id":"INV-7","total":"49.50 USD"}
Circular references
An object that refers to itself cannot be written as JSON — it would never end:
const node = { name: "root" };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log(err.name);
console.log(err.message.split("\n")[0]);
}TypeError
Converting circular structure to JSON
Test yourself
What does JSON.stringify({a: undefined, b: 1}) return?
- '{"a":null,"b":1}'
- '{"a":undefined,"b":1}'
- '{"b":1}'
- A TypeError
What is the third argument of JSON.stringify() for?
- The maximum depth
- Indentation (pretty printing)
- The character encoding
- A list of keys to skip
Which value makes JSON.stringify throw a TypeError?
- NaN
- A Date
- A BigInt like 10n
- A function