22.5. Serialize Dates, Maps and Sets to JSON and back
Topics
This question is in
22. SerializationSave 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
function serialize(value) // returns a string of JSON
function deserialize(text) // returns the rebuilt valueThe 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:
| Value | Written 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
- Plain JSON data with no own
$typekey at any depth and no-0is written exactly asJSON.stringifywrites it, and JSON text with no$typekey is read asJSON.parsereads it. The output is always valid JSON. - Dates come back as
Dateobjects with the same time, at any depth. An invalid Date comes back as an invalid Date. - Maps come back as
Maps with the same entries in the same order. Keys keep their type:1and"1"stay different keys, and object,NaNandDatekeys work. - Sets come back as
Sets with the same members in the same order. - Empty Maps, Sets, arrays and objects come back, and all of these work nested inside each other.
undefinedcomes back: as an object property (the key is still there), as an array item, and at the top level.NaN,Infinity,-Infinityand-0come back as themselves; BigInts come back as the same bigint.- A plain object with its own
$typekey, at any depth, comes back as a plain object, not as the value its tag names. Strings are never treated as tags. - Rebuilt objects are ordinary objects (with
Object.prototype). Every key is kept as an own property, on both sides, including__proto__. serializedoes not change its input.- A tag object in the text is read as the value it names, even when
serializedid not write it.deserializethrows aTypeErrorfor a$typeit does not know. - A rebuilt value serializes to the same text again.
Examples
serialize({ when: new Date(0), tags: new Set(["a"]) });
// '{"when":{"$type":"Date","value":"1970-01-01T00:00:00.000Z"},"tags":{"$type":"Set","value":["a"]}}'const back = deserialize(serialize(new Map([[1, "one"], ["1", "string one"]])));
back.get(1); // "one"
back.get("1"); // "string one"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 DateEnvironment
- Plain JavaScript in a browser page; the tests call the globals
serializeanddeserializefromserialize.js. JSON.stringifyandJSON.parseare allowed.- Out of scope: functions, symbols, class instances other than
Date,MapandSet, array holes, shared objects and cycles (a value reached twice comes back as two copies).
Hints
JSON.stringifycalls a Date'stoJSONbefore a replacer sees it. Is it easier to fix that inside a replacer, or to build a JSON-safe copy first?- A reviver that returns
undefineddeletes 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