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

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

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?)

const jsonString = '{"name":"Alice","age":25}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // "Alice"

Transforming values with reviver

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

Common Use Cases

Deep Copy an Object

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.

Handling Circular References