CPCODELAB
JavaScript

JSON.parse and JSON.stringify in Depth

9 min read

Working with JSON

JSON (JavaScript Object Notation) is the universal data-interchange format for web APIs. Two built-in functions handle the conversion between JSON strings and JavaScript values: JSON.stringify (JS → string) and JSON.parse (string → JS).

js
const user = { name: "Alice", age: 30, active: true };

// Serialize to JSON string
const json = JSON.stringify(user);
// '{"name":"Alice","age":30,"active":true}'

// Pretty-print with 2-space indent
console.log(JSON.stringify(user, null, 2));

// Parse back to a JS object
const parsed = JSON.parse(json);
console.log(parsed.name); // "Alice"

The Replacer and Reviver

Both functions accept an optional second argument for fine-grained control. stringify accepts a replacer (array of keys to include, or a function). parse accepts a reviver function that transforms each value after parsing.

js
// Replacer: only serialise specific keys
const data = { name: "Bob", password: "s3cr3t", score: 99 };
JSON.stringify(data, ["name", "score"]);
// '{"name":"Bob","score":99}'

// Reviver: convert date strings back to Date objects
const withDate = '{"created":"2025-01-15T00:00:00.000Z"}';
const obj = JSON.parse(withDate, (key, value) => {
  if (key === "created") return new Date(value);
  return value;
});
console.log(obj.created instanceof Date); // true

Values that JSON cannot represent — undefined, functions, Symbol, and BigInt — are silently dropped by JSON.stringify. Date objects become ISO strings; you must revive them manually. NaN and Infinity become null.

A common pattern for a fast deep-clone of a plain object (no functions, no Dates) is JSON.parse(JSON.stringify(obj)). It is simple but lossy — use a dedicated library like structuredClone (built-in since Node 17) for production cloning.

js
const original = { a: 1, b: { c: 2 } };

// Modern deep clone — handles Dates, Maps, Sets, and more
const clone = structuredClone(original);
clone.b.c = 99;
console.log(original.b.c); // 2 — not mutated
Ready to test yourself?
Practice JavaScript— quiz & coding exercises