JSON.stringify() turns a JavaScript value into a JSON string.
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.
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
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 becomenullinside arrays).Dateobjects become ISO strings (they have atoJSONmethod).NaNandInfinitybecomenull.- Maps and Sets turn into
{}(convert them first:[...map],[...set]).
Choosing properties: the replacer
An array of keys keeps only those properties:
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:
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.
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.
const a = {};
a.self = a;
try {
JSON.stringify(a);
} catch (error) {
console.log(error.name); // → TypeError
}
BigInt throws
try {
JSON.stringify({ id: 10n });
} catch (error) {
console.log(error.name); // → TypeError
}
Convert big numbers to strings first.
Remember
stringify is for data. Functions, DOM elements and class behaviour are not part of JSON, so only the data survives the trip.