Tuesday, November 26, 2019

ES6 Recipe: JSON.stringify Map

The keys of a Map can be anything, including objects. But JSON syntax only allows strings as keys...

Let's stringify Map instance to JSON...

Serialize Map instance to JSON

We can't directly stringify the Map instance, therefore we need to convert it to Array first and than stringify.

TypeScript
JSON.stringify(Array.from([...map]))
// or
JSON.stringify(Array.from(map))
// or
JSON.stringify(Array.from(map.entries()))

Output would be exactly the same in all three cases above.

TypeScript
// [["key1", "value"],["key2", "value"]]

Deserialize your JSON string back to Map

TypeScript
const mapJSON = JSON.stringify([...map])
const deserializedMap = new Map(JSON.parse(mapJSON));

Stringify Map instance with objects as keys

Let's create the Map with objects as keys:

TypeScript
const map = new Map();
map.set({ label: 'opt1' }, true);
map.set({ label: 'opt2' }, false);

JSON.stringify(Array.from([...map]))

Output should be the following.

TypeScript
// [[{"label":"opt1"},true],[{"label":"opt2"},false]]

Conclusion

In case your keys are strings, you could still use the plain object as a map.
It would be easily stringified and sometimes even faster.


see Also


1 comment: