Glossary / JSON serialization
JSON serialization
JSON serialization converts a restricted set of JavaScript values to JSON text with JSON.stringify; JSON.parse converts valid JSON text back to JavaScript values. JSON is a data-interchange format, not a lossless snapshot of arbitrary JavaScript object graphs. Serialization can omit values, transform them, or throw, so wire formats need explicit contracts.
Conversion behavior
JSON.stringify({ a: undefined, b: null }); // '{"b":null}'
JSON.stringify([undefined, , NaN]); // '[null,null,null]'
Object properties with undefined, functions, or Symbols are omitted; in arrays those positions become null. NaN and infinities serialize as null. BigInt throws unless explicitly converted. Dates usually call toJSON and become ISO strings. Cycles throw TypeError. Prototypes, property descriptors, Map/Set membership, object identity, and private fields are not preserved by default. Replacer and reviver callbacks can customize transformations but must be designed as part of the schema.
JSON.parse checks JSON syntax, not application validity. Validate shape, allowed keys, types, ranges, and trust boundaries afterward. Parsing large integers into Number may lose precision. Do not insert serialized JSON into HTML unsafely; HTML and JavaScript embedding require context-aware encoding.
Wire-format design
Define representations for dates, large integers, binary data, and optional fields. Avoid ambiguous sentinels and version schemas when evolving APIs. Test round trips only for the subset of values the contract promises to preserve.
Interview questions
- Does JSON preserve undefined? No; object properties are omitted and array positions become null.
- What happens to Date? Typically its
toJSONreturns an ISO string. - Does JSON preserve prototypes or Map entries? No, not by default.
- Does parse validate an API payload? It validates JSON syntax only; application schema validation is separate.
- What happens to BigInt? Stringify throws unless a custom representation is provided.