TExcelTAD
Home › JSON › JSON.stringify()

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.

js
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)

Basic use

js · try it yourself
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
js · try it yourself
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 Set or Map, convert it first: [...mySet] or Object.fromEntries(myMap).

The replacer

The second argument controls what gets included.

An array of keys acts as an allow-list:

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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:

js · try it yourself
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?

  1. '{"a":null,"b":1}'
  2. '{"a":undefined,"b":1}'
  3. '{"b":1}'
  4. A TypeError

What is the third argument of JSON.stringify() for?

  1. The maximum depth
  2. Indentation (pretty printing)
  3. The character encoding
  4. A list of keys to skip

Which value makes JSON.stringify throw a TypeError?

  1. NaN
  2. A Date
  3. A BigInt like 10n
  4. A function