JSON.stringify() is one of the most frequently used JavaScript functions — and one of the most misunderstood. Most developers know it converts objects to strings, but the function's full power lies in its optional replacer and space parameters, which most tutorials never even mention.
This guide covers everything: basic usage, pretty-printing, filtering keys, handling circular references, custom serialization via toJSON(), and the edge cases that trip up even experienced JavaScript developers.
JSON stringify tutorial placement
Advertisement placeholder -- this space is reserved for contextual ads once the site is approved.
Basic Usage
The simplest form converts any serializable JavaScript value to a JSON string:
const user = { name: "Alice", age: 30, active: true };
JSON.stringify(user);
// '{"name":"Alice","age":30,"active":true}'
// Arrays work too
JSON.stringify([1, "two", true, null]);
// '[1,"two",true,null]'
// Primitives
JSON.stringify(42); // '42'
JSON.stringify("hello"); // '"hello"'
JSON.stringify(null); // 'null'What Gets Omitted
JSON.stringify() silently drops certain values — a common source of bugs:
undefinedvalues in objects are omitted entirely- Functions are omitted
Symbolkeys and values are omittedInfinityandNaNbecomenull
const obj = {
name: "Alice",
age: undefined, // omitted
greet: () => {}, // omitted
score: Infinity, // becomes null
};
JSON.stringify(obj);
// '{"name":"Alice","score":null}'Pretty-Printing with the space Parameter
The third argument to JSON.stringify() controls indentation. Pass a number for spaces, or a string (like "\t") for tabs:
const data = { name: "Alice", scores: [95, 87, 92] };
console.log(JSON.stringify(data, null, 2));
// {
// "name": "Alice",
// "scores": [
// 95,
// 87,
// 92
// ]
// }This is exactly what JSONStudio does when you click "Format" — it calls the equivalent of JSON.stringify(parsed, null, 2) to produce human-readable output.
Mid-article stringify placement
Advertisement placeholder -- this space is reserved for contextual ads once the site is approved.
The replacer Parameter
The second argument is a replacer — either an array of keys to include, or a function to transform values:
const user = { id: 1, name: "Alice", password: "secret", age: 30 };
// Array replacer: only include specific keys
JSON.stringify(user, ["name", "age"], 2);
// '{"name":"Alice","age":30}'
// Function replacer: transform or filter values
JSON.stringify(user, (key, value) => {
if (key === "password") return undefined; // omit sensitive fields
if (typeof value === "number") return value * 2; // transform numbers
return value;
}, 2);
// '{"id":2,"name":"Alice","age":60}'Custom toJSON() Method
Objects can define a toJSON() method to control their own serialization:
class Money {
constructor(amount, currency) {
this.amount = amount;
this.currency = currency;
}
toJSON() {
return `${this.currency} ${this.amount.toFixed(2)}`;
}
}
const price = new Money(9.9, "USD");
JSON.stringify({ price });
// '{"price":"USD 9.90"}'Handling Circular References
JSON.stringify() throws a TypeError when it encounters a circular reference. The most common fix is a replacer that tracks seen objects:
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
}
const a = { name: "Alice" };
a.self = a; // circular reference
console.log(safeStringify(a));
// '{"name":"Alice","self":"[Circular]"}'Key Takeaways
undefined, functions, and Symbols are silently dropped- Use the
spaceparameter for human-readable output - Use an array
replacerto whitelist fields, or a function to transform values - Define
toJSON()on custom classes for clean serialization - Use a
WeakSet-based replacer to handle circular references
Continue learning
What is JSON?
A foundational tour of JSON covering syntax, design goals, and why it became the lingua franca for data on the web.
Jan 5, 2025 · 9 min read
How JSON Works
Learn how parsers tokenize documents, how serialization travels across the network, and ways to debug encoding bugs.
Jan 6, 2025 · 10 min read
JSON vs XML
An objective look at how both formats handle validation, streaming, and readability so you can choose for each project.
Jan 7, 2025 · 11 min read