JSON.stringify()

Beginner
⏱️ 9 min read
📚 Updated: May 2026
Serialization

What you’ll learn

JSON is how browsers and servers exchange structured data as text. After JSON.parse() turns text into values, JSON.stringify() does the opposite: it produces a JSON string you can send over the network, write to disk, or log.

This guide covers the three-argument signature, the replacer (function or whitelist array), the space formatter, and what happens with circular object graphs.

What JSON.stringify() does

The method walks a JavaScript value and emits UTF‑16 JSON text. Only JSON‑representable data survives: for example Date becomes an ISO‑8601 string, functions and symbols are normally skipped, and BigInt throws unless you convert it yourself.

Syntax

JavaScript
JSON.stringify(value[, replacer[, space]])
value
The value to serialize: an object, array, string, number, boolean, or null.
replacer
Optional. Either a function (key, value) => newValue to transform values or return undefined to omit a property, or an array of property names to whitelist (array indices appear as string keys). Root key is "" when the replacer runs on the top-level value.
space
Optional. Indentation: a number from 1 to 10 (spaces per level), or a non-empty string used as a prefix per level, for readable multi-line JSON. Use 0, '', or omit for compact output.
1

Basic usage

By default, objects stringify to a compact single line with no indentation. Key order follows the object’s own enumerable string keys as enumerated by the engine (do not rely on key order across runtimes for protocol semantics).

JavaScript
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
Result
{"name":"John","age":30,"city":"New York"}
2

Replacer as a function

When the replacer returns undefined for a nested property, that property is omitted from the JSON string. Here we drop every string-valued field and keep numbers.

JavaScript
const obj = { name: "John", age: 30, city: "New York" };

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

const jsonString = JSON.stringify(obj, replacer);
console.log(jsonString);
Result
{"age":30}

Here every string property is dropped; numbers remain.

3

Replacer as an array (whitelist)

When replacer is an array, only listed keys are serialized (in the order they appear in the array).

JavaScript
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj, ["name", "city"]);
console.log(jsonString);
Result
{"name":"John","city":"New York"}
4

Space (indentation)

Pass a number (max effective 10) or a string as the third argument to insert indentation and line breaks. Use 0 or omit the argument for compact output in production logs and APIs.

JavaScript
const obj = { name: "John", age: 30, city: "New York" };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
Result
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
5

Circular references

JSON is a tree, not a general graph. If an object appears twice on the same path through references, JSON.stringify throws TypeError (message text varies by engine).

JavaScript
const obj = {};
obj.self = obj;

try {
  JSON.stringify(obj);
} catch (error) {
  console.log(error.name, error.message);
}
Typical output
TypeError Converting circular structure to JSON

Mitigations: design APIs around acyclic DTOs; use a custom replacer that replaces already‑seen objects with null or an id; use a small library such as flatted for lossless cycle encoding; or log a shallow copy for debugging.

Key takeaways

1

JSON.stringify(value) produces JSON text suitable for HTTP bodies and storage.

2

The replacer filters or rewrites values; the space argument controls pretty printing.

3

Cycles throw TypeError; plan your data shape or use a cycle‑safe strategy before logging complex graphs.

Frequently asked questions

A string containing JSON text. For most objects the default is a compact line with no extra whitespace unless you pass a space argument.
Own properties whose value is undefined are omitted from objects. In arrays, a missing or undefined element becomes null in the JSON. Top‑level JSON.stringify(undefined) is undefined, not a string.
Use a function replacer to return undefined to drop a key, or return a new value to substitute. Alternatively pass an array of allowed key names to act as a whitelist.
JSON cannot encode graphs with back‑edges. The built‑in serializer detects revisiting the same object chain and throws. Break cycles, serialize a DTO, or use a dedicated encoding library.

Next: JSONP

See how older sites loaded cross‑origin JSON before CORS was ubiquitous—and why modern code prefers JSON over script injection.

JSONP →
Did you know?

Object properties whose value is undefined are typically omitted from JSON.stringify output, while undefined inside an array becomes null. Date values become ISO‑8601 strings. BigInt is not JSON‑serializable and throws unless you convert it first.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful