How to Convert a Map to JSON in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

banner

Photo by Redd

Convert a Map to JSON in JavaScript #

To convert a Map to JSON, use the Object.fromEntries() method to convert the Map to an object and pass the result to the JSON.stringify() method. The JSON.stringify method converts the passed in value to a JSON string and returns the result.

index.js
const map = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // โœ… Convert to JSON string const json = JSON.stringify(Object.fromEntries(map)); // ๐Ÿ‘‡๏ธ '{"name": "Tom", "country": "Chile"}' console.log(json);

We used the Object.fromEntries method to convert a Map to an object.

index.js
const map = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); const obj = Object.fromEntries(map); console.log(obj) // ๐Ÿ‘‰๏ธ {name: 'Tom', country: 'Chile'}
We had to do this, because Map objects don't have native support for serialization or parsing.

The next step is to use the JSON.stringify method, passing it the object.

The JSON.stringify method converts the object into a JSON string and returns the result.

If you need to convert the JSON string back into a Map, you have to:

  1. use the JSON.parse method to parse the JSON string into an object
  2. use the Object.entries method to get an array of key-value pairs
  3. call the Map() constructor with the array of key-value pairs
index.js
const map = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); const json = JSON.stringify(Object.fromEntries(map)); const obj = JSON.parse(json); const mapAgain = new Map(Object.entries(obj)); console.log(mapAgain); // ๐Ÿ‘‰๏ธ {'name' => 'Tom', 'country' => 'Chile'}

The Object.entries method takes an object and returns a two-dimensional array.

index.js
// ๐Ÿ‘‡๏ธ [['name', 'Tom'], ['country', 'Chile']] console.log(Object.entries({name: 'Tom', country: 'Chile'}));

The Map() constructor expects an iterable whose elements are key-value pairs, so we directly pass it the result from calling the Object.entries method.

To get around the fact that Map objects don't have native support for serialization or parsing, we convert the Map to an object and serialize the object.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee