Skip to curriculum
Jump to the editor

22.5. Serialize Dates, Maps and Sets to JSON and back

Hard
Topics

This question is in

22. Serialization
30–50 min

Save an app's state to localStorage with JSON.stringify, load it back with JSON.parse, and much of it has changed shape: every Date is now a string, every Map and Set is an empty object {}, keys set to undefined are gone, and NaN is null. A BigInt does not even get that far: it throws. Apps that keep such state, and messaging layers that send it, use a small tagged format: each value JSON cannot hold is written as an object that says what it was.

Write serialize(value) and deserialize(text) in serialize.js, using the format below, so that deserialize(serialize(value)) gives back a value equal to value.

Signature

JAVASCRIPT
function serialize(value)   // returns a string of JSON
function deserialize(text)  // returns the rebuilt value

The format

Plain JSON data (objects, arrays, strings, finite numbers, booleans, null) is written as JSON writes it, with two exceptions shown in the table: -0, and an object that has its own $type key. Every other supported value becomes an object with a $type key:

ValueWritten as
a Date{"$type":"Date","value":"1970-01-01T00:00:00.000Z"}, the ISO string; null for an invalid Date
a Map{"$type":"Map","value":[[key, value], …]}, keys and values encoded the same way
a Set{"$type":"Set","value":[member, …]}, members encoded
undefined{"$type":"undefined"}
NaN, Infinity, -Infinity, -0{"$type":"Number","value":"NaN"} (or "Infinity", "-Infinity", "-0")
a bigint{"$type":"BigInt","value":"12345"}, its digits
a plain object that has its own $type key{"$type":"Object","value":{…its properties, encoded}}

Members of the tag objects are written in the order shown ($type first, then value). deserialize reads this format: in the text, every object with its own $type key is a tag, whoever wrote it, and an object without one is plain data.

Requirements

  1. Plain JSON data with no own $type key at any depth and no -0 is written exactly as JSON.stringify writes it, and JSON text with no $type key is read as JSON.parse reads it. The output is always valid JSON.
  2. Dates come back as Date objects with the same time, at any depth. An invalid Date comes back as an invalid Date.
  3. Maps come back as Maps with the same entries in the same order. Keys keep their type: 1 and "1" stay different keys, and object, NaN and Date keys work.
  4. Sets come back as Sets with the same members in the same order.
  5. Empty Maps, Sets, arrays and objects come back, and all of these work nested inside each other.
  6. undefined comes back: as an object property (the key is still there), as an array item, and at the top level.
  7. NaN, Infinity, -Infinity and -0 come back as themselves; BigInts come back as the same bigint.
  8. A plain object with its own $type key, at any depth, comes back as a plain object, not as the value its tag names. Strings are never treated as tags.
  9. Rebuilt objects are ordinary objects (with Object.prototype). Every key is kept as an own property, on both sides, including __proto__.
  10. serialize does not change its input.
  11. A tag object in the text is read as the value it names, even when serialize did not write it. deserialize throws a TypeError for a $type it does not know.
  12. A rebuilt value serializes to the same text again.

Examples

JAVASCRIPT
serialize({ when: new Date(0), tags: new Set(["a"]) });
// '{"when":{"$type":"Date","value":"1970-01-01T00:00:00.000Z"},"tags":{"$type":"Set","value":["a"]}}'
JAVASCRIPT
const back = deserialize(serialize(new Map([[1, "one"], ["1", "string one"]])));
back.get(1);     // "one"
back.get("1");   // "string one"
JAVASCRIPT
deserialize(serialize({ a: undefined, n: NaN, z: -0 }));
// { a: undefined, n: NaN, z: -0 }

deserialize(serialize({ $type: "Date", value: "x" }));
// { $type: "Date", value: "x" }: a plain object, not a Date

Environment

  • Plain JavaScript in a browser page; the tests call the globals serialize and deserialize from serialize.js.
  • JSON.stringify and JSON.parse are allowed.
  • Out of scope: functions, symbols, class instances other than Date, Map and Set, array holes, shared objects and cycles (a value reached twice comes back as two copies).

Hints

  1. JSON.stringify calls a Date's toJSON before a replacer sees it. Is it easier to fix that inside a replacer, or to build a JSON-safe copy first?
  2. A reviver that returns undefined deletes the property. What does that mean for { a: undefined }, and for a tag that sits inside an escaped object?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…