JSON.stringify(value, replacer?, space?)
value
: The object or value to convert.replacer
(optional): A function or array to filter properties.space
(optional): Indentation level for formatting.const obj = { name: "Alice", age: 25 };
console.log(JSON.stringify(obj));
// '{"name":"Alice","age":25}'
// Pretty-print with indentation
console.log(JSON.stringify(obj, null, 2));
/*
{
"name": "Alice",
"age": 25
}
*/
Filtering properties with replacer
replacer
can be a function or an array that filters which properties are included.const user = { name: "Alice", age: 25, password: "secret" };
// Exclude `password`
console.log(JSON.stringify(user, ["name", "age"]));
// '{"name":"Alice","age":25}'
console.log(
JSON.stringify(user, (key, value) => key === "password" ? undefined : value)
);
// '{"name":"Alice","age":25}'
JSON.parse(jsonString, reviver?)
jsonString
: The string to parse.reviver
(optional): A function to transform the result.const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "Alice"
Transforming values with reviver
reviver
allows modification of parsed values.const data = '{"date":"2024-03-18T12:00:00.000Z"}';
const parsed = JSON.parse(data, (key, value) =>
key === "date" ? new Date(value) : value
);
console.log(parsed.date instanceof Date); // true
console.log(parsed.date.getFullYear()); // 2024
JSON.stringify()
+ JSON.parse()
is a simple way to create a deep copy:
const obj = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 42;
console.log(obj.b.c); // 2 (original object remains unchanged)
Does not preserve undefined
, functions, Symbol
, Map
, Set
, RegExp
, or BigInt
.