Skip to content

JavaScript Tutorial JSON

JavaScript JSON.stringify()

Lesson 133 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

JSON.stringify() turns a JavaScript value into a JSON string.

script.js
JS
const user = { name: "Maya", age: 28, skills: ["js", "css"] };

const text = JSON.stringify(user);
console.log(text);          // → {"name":"Maya","age":28,"skills":["js","css"]}
console.log(typeof text);   // → string

Pretty printing

The third argument adds indentation, which helps when you log or display data.

script.js
JS
const user = { name: "Maya", skills: ["js", "css"] };
console.log(JSON.stringify(user, null, 2));

The null is the replacer (next), and 2 is the number of spaces.

What happens to different values

script.js
JS
const value = {
  string: "text",
  number: 1,
  yes: true,
  nothing: null,
  missing: undefined,          // skipped
  fn() {},                     // skipped
  symbol: Symbol("x"),         // skipped
  date: new Date(0),           // becomes a string
  nan: NaN                     // becomes null
};

console.log(JSON.stringify(value));
// → {"string":"text","number":1,"yes":true,"nothing":null,"date":"1970-01-01T00:00:00.000Z","nan":null}
  • undefined, functions and symbols disappear from objects (and become null inside arrays).
  • Date objects become ISO strings (they have a toJSON method).
  • NaN and Infinity become null.
  • Maps and Sets turn into {} (convert them first: [...map], [...set]).

Choosing properties: the replacer

An array of keys keeps only those properties:

script.js
JS
const user = { name: "Maya", password: "secret", age: 28 };
console.log(JSON.stringify(user, ["name", "age"])); // → {"name":"Maya","age":28}

A function can filter or change values:

script.js
JS
const user = { name: "Maya", password: "secret" };
const safe = JSON.stringify(user, (key, value) => (key === "password" ? undefined : value));
console.log(safe); // → {"name":"Maya"}

toJSON

If an object has a toJSON() method, stringify uses its result.

script.js
JS
const money = {
  amount: 12.5,
  currency: "USD",
  toJSON() { return `${this.amount} ${this.currency}`; }
};
console.log(JSON.stringify({ price: money })); // → {"price":"12.5 USD"}

Circular references

An object that contains itself cannot be turned into JSON.

script.js
JS
const a = {};
a.self = a;

try {
  JSON.stringify(a);
} catch (error) {
  console.log(error.name); // → TypeError
}

BigInt throws

script.js
JS
try {
  JSON.stringify({ id: 10n });
} catch (error) {
  console.log(error.name); // → TypeError
}

Convert big numbers to strings first.

lightbulb
Remember
stringify is for data. Functions, DOM elements and class behaviour are not part of JSON, so only the data survives the trip.