JavaScript theorytheory 0/50 · 0%
Data · medium

32. JSON and serialisation

Parsing, stringifying and BigInt pitfalls.

`JSON.parse` and `JSON.stringify` handle strings, numbers, booleans, null, arrays and plain objects. They drop `undefined` and functions, and throw on BigInt and circular references.

JSON.stringify({ v: 1n }); // TypeError
JSON.stringify(obj, (k, v) => typeof v === "bigint" ? v.toString() : v);

Always wrap `JSON.parse` of untrusted input in try/catch.

Check your understanding

  1. 1. What does `JSON.stringify` do with a BigInt?

  2. 2. What happens to `undefined` properties?

  3. 3. Why guard `JSON.parse`?