Blog post
JSON.stringify() Complete Guide: Options, Replacer, and Space Parameter
Master JSON.stringify() in JavaScript — replacer functions, space parameter for pretty-printing, handling undefined/circular references, and performance tips.
Shashank Jain
Author


Article
What is JSON.stringify()?
JSON.stringify() converts a JavaScript value to a JSON string. It is the primary way to serialize objects for APIs, local storage, and logging.
Basic Syntax
JSON.stringify(value, replacer, space)- value — the value to serialize
- replacer — optional function or array to filter/transform keys
- space — optional indentation (number of spaces or string)
Pretty-Printing with the Space Parameter
const obj = { name: 'Alice', age: 30 };
console.log(JSON.stringify(obj, null, 2));
// Output:
// {
// "name": "Alice",
// "age": 30
// }Filtering Keys with a Replacer Array
const user = { id: 1, name: 'Alice', password: 'secret' };
JSON.stringify(user, ['id', 'name']);
// '{"id":1,"name":"Alice"}' — password excludedTransforming Values with a Replacer Function
JSON.stringify(data, (key, value) => {
if (value === undefined) return null; // preserve undefined as null
if (typeof value === 'bigint') return value.toString();
return value;
});What JSON.stringify() Silently Drops
| Value | In object | In array |
|---|---|---|
| undefined | Key dropped | Becomes null |
| function | Key dropped | Becomes null |
| Symbol | Key dropped | Becomes null |
| NaN / Infinity | Becomes null | Becomes null |
Handling Circular References
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;
});
}Use the JSON formatter at jsondecode.com to validate and pretty-print your JSON output.
Keep reading
Recent blogs

Jun 14, 2026
JSON in C#: System.Text.Json and Newtonsoft Complete Guide
Serialize and deserialize JSON in C# using System.Text.Json and Newtonsoft.Json with practical examples.

Jun 14, 2026
JSON to Markdown Table: Convert JSON Arrays Instantly
Convert JSON arrays to Markdown tables in JavaScript, Python, and with the free online tool.

Jun 14, 2026
JSON in TypeScript: Type-Safe Parsing and Validation
Stop using any for JSON in TypeScript — use Zod, type guards, and generics for fully type-safe parsing.