How do you JSON.stringify an ES6 Map?

rynop picture rynop · Mar 16, 2015 · Viewed 57.1k times · Source

I'd like to start using ES6 Map instead of JS objects but I'm being held back because I can't figure out how to JSON.stringify() a Map. My keys are guaranteed to be strings and my values will always be listed. Do I really have to write a wrapper method to serialize?

Answer

Bergi picture Bergi · Nov 24, 2018

You can't directly stringify the Map instance as it doesn't have any properties, but you can convert it to an array of tuples:

jsonText = JSON.stringify(Array.from(map.entries()));

For the reverse, use

map = new Map(JSON.parse(jsonText));