← Back to JavaScript, page 3

javascript-0054 · Medium mid

What are the edge cases and pitfalls of JSON.stringify and JSON.parse?

JSON.stringify drops undefined, functions, and symbols in objects, turns them into null in arrays, converts NaN and Infinity to null, turns Dates into strings, throws on BigInt and circular references, and skips non-enumerable keys. JSON.parse never restores types by itself, and throws on invalid JSON. toJSON, replacer, and reviver let you control both directions.

Full answer

JSON is a text format with only six kinds of value: object, array, string, number, boolean, and null. Anything else has to be converted, and JSON.stringify makes quiet choices.

In objects, properties whose value is undefined, a function, or a symbol are skipped. In arrays, those same values become null to keep the positions. NaN, Infinity, and -Infinity become null. A Date has a toJSON method, so it becomes an ISO string, and Map, Set, and class fields that are private become {} or are absent. A BigInt throws a TypeError, and a circular reference throws a TypeError too. Only own, enumerable, string-keyed properties are written. If an object has a toJSON method, its return value is serialized instead.

JSON.parse turns text back into plain data. A date string stays a string, and a number stays a number, so types such as Date and Map are not restored. Invalid JSON throws a SyntaxError: single quotes, trailing commas, comments, and unquoted keys are not allowed. Large integers beyond 2^53 lose precision when parsed as numbers.

The second argument of stringify is a replacer, which is either a function or an array of allowed keys. The second argument of parse is a reviver, called for each key and value from the inside out, which is the place to rebuild dates. The third argument of stringify sets the indentation.

A __proto__ key in parsed JSON creates an ordinary own property, not a prototype change. Still, merging parsed objects unsafely can be dangerous, which is covered in the prototype pollution question.

javascript
const data = {
  title: 'Report',
  draft: undefined,
  run() {},
  id: Symbol('x'),
  ratio: NaN,
  limit: Infinity,
  createdAt: new Date('2026-02-01T08:00:00Z'),
  tags: new Set(['a']),
  list: [undefined, () => 1, 3],
};
console.log(JSON.stringify(data));

try {
  JSON.stringify({ big: 10n });
} catch (error) {
  console.log('BigInt:', error.name);
}
const loop = {};
loop.self = loop;
try {
  JSON.stringify(loop);
} catch (error) {
  console.log('circular:', error.name);
}

class Money {
  constructor(amount, currency) {
    this.amount = amount;
    this.currency = currency;
  }
  toJSON() {
    return `${this.amount} ${this.currency}`;
  }
}
console.log(JSON.stringify({ price: new Money(250, 'INR') }));
console.log(JSON.stringify({ a: 1, b: 2, c: 3 }, ['a', 'c']));
console.log(JSON.stringify({ a: 1, b: { c: 2 } }, (key, value) => (typeof value === 'number' ? value * 10 : value), 2));

const text = JSON.stringify({ when: new Date('2026-02-01T08:00:00Z'), n: 1 });
const plain = JSON.parse(text);
console.log(typeof plain.when);
const revived = JSON.parse(text, (key, value) => (key === 'when' ? new Date(value) : value));
console.log(revived.when instanceof Date, revived.when.getUTCFullYear());

for (const bad of ["{'a': 1}", '{"a": 1,}', '{a: 1}', '']) {
  try {
    JSON.parse(bad);
  } catch (error) {
    console.log(JSON.stringify(bad), '->', error.name);
  }
}
console.log(JSON.parse('{"__proto__": {"admin": true}}').admin, Object.keys(JSON.parse('{"__proto__": 1}')));
console.log(JSON.parse('12345678901234567890'));

Run with Node.js v24.22.1 as js-54.js; two runs gave identical output. Output: {"title":"Report","ratio":null,"limit":null,"createdAt":"2026-02-01T08:00:00.000Z","tags":{},"list":[null,null,3]} BigInt: TypeError circular: TypeError {"price":"250 INR"} {"a":1,"c":3} { "a": 10, "b": { "c": 20 } } string true 2026 "{'a': 1}" -> SyntaxError "{\"a\": 1,}" -> SyntaxError "{a: 1}" -> SyntaxError "" -> SyntaxError undefined [ '__proto__' ] 12345678901234567000

Key points

  • Only own enumerable string keys are written; undefined, functions, and symbols are skipped in objects and become null in arrays.
  • NaN and Infinity become null; BigInt and circular structures throw.
  • Dates become ISO strings and are not restored by parse.
  • toJSON, replacer, and reviver control the conversion in each direction.
  • Invalid JSON, including trailing commas and single quotes, throws SyntaxError.

Common mistakes

  • Using JSON.parse(JSON.stringify(x)) as a general deep copy for data with dates, undefined, Map, or Set.
  • Expecting dates to come back as Date objects after parse.
  • Parsing user input without a try/catch.
  • Storing large integer IDs as JSON numbers and losing precision.

Follow-ups

  • How would you serialize and restore a Map?
  • How would you send a BigInt in JSON safely?
  • What does JSON.stringify do with a property whose value is an object with a toJSON method?

Tips

  • List the "quietly dropped" values as a short group; this is what interviewers ask for.
  • Show a reviver for dates; it proves you know how to round-trip data.
  • Mention that single quotes, trailing commas, and comments are invalid JSON.