Back to NiceJSON
NiceJSON Blog/ JSON.parse and JSON.stringify in JavaScript: Complete Guide

JSON.parse and JSON.stringify in JavaScript: Complete Guide

Master JSON.parse and JSON.stringify: reviver and replacer functions, pretty printing, handling dates, circular references, BigInt, and error handling.

2 min read
  • json
  • javascript
  • tutorial

The two core functions

JavaScript has two built-in functions for JSON:

  • JSON.parse(text) converts a JSON string into a JavaScript value.
  • JSON.stringify(value) converts a JavaScript value into a JSON string.
const text = '{"name":"Ada","age":36}';
const user = JSON.parse(text);
console.log(user.age); // 36
 
const out = JSON.stringify(user);
console.log(out); // {"name":"Ada","age":36}

Always handle parse errors

JSON.parse throws a SyntaxError on invalid input, so wrap untrusted input in try/catch.

function safeParse(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    return { ok: false, error: error.message };
  }
}

If you do not know why a string fails, paste it into the NiceJSON validator to locate the error.

Pretty printing with stringify

The third argument sets indentation:

JSON.stringify({ a: 1, b: [1, 2] }, null, 2);

The second argument is the replacer. Pass an array to pick keys, or a function to transform values:

const user = { name: "Ada", password: "secret", age: 36 };
 
JSON.stringify(user, ["name", "age"]);
// {"name":"Ada","age":36}
 
JSON.stringify(user, (key, value) =>
  key === "password" ? undefined : value
);

Reviving values with parse

JSON.parse takes an optional reviver that runs on each value. It is the standard way to turn date strings back into Date objects.

const text = '{"created":"2026-11-04T10:00:00.000Z"}';
 
const obj = JSON.parse(text, (key, value) =>
  key === "created" ? new Date(value) : value
);
 
console.log(obj.created instanceof Date); // true

What stringify drops or changes

ValueResult
undefined, functions, symbols in objectsOmitted
undefined in arraysnull
NaN, Infinitynull
DateISO string via toJSON()
Map, Set{} (empty object)
BigIntThrows TypeError

Fixing BigInt

JSON.stringify({ id: 12345678901234567890n }, (_, v) =>
  typeof v === "bigint" ? v.toString() : v
);

Circular references

const a = {};
a.self = a;
JSON.stringify(a); // TypeError: Converting circular structure to JSON

Break the cycle manually, or use a library that supports reference handling.

Deep copy caveat

JSON.parse(JSON.stringify(x)) is a common deep clone trick, but it loses dates, undefined, Map, and Set. Prefer structuredClone(x) in modern runtimes.

Security reminder

Never use eval() to parse JSON. JSON.parse is safe because it only accepts data, never executable code.