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

May 22, 2026
JSONPath Guide: Query JSON Data Like SQL (with Examples)
Learn JSONPath syntax to query JSON data — basic expressions, wildcards, filters, recursive descent, and array slices. Includes JavaScript and Python examples.

May 22, 2026
How to Convert JSON to TypeScript Interfaces Automatically
Learn how to convert JSON to TypeScript interfaces — manually, with tools, and with AI. Includes nested objects, arrays, optional fields, and Zod schema generation.

May 22, 2026
JSON Schema Validation: A Complete Guide with Examples
Learn JSON Schema validation from scratch — Draft 7 syntax, required fields, type constraints, pattern matching, array validation, and validation with AJV in JavaScript.