How to Convert a Map to JSON in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert a Map to JSON in JavaScript #

To convert a Map to JSON:

  1. Use the Object.fromEntries() method to convert the Map to an object.
  2. Pass the object to the JSON.stringify() method.
  3. The JSON.stringify() method converts the passed in value to a JSON string.
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 pass the object to the JSON.stringify method.

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

If you need to convert the JSON string back to 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 can 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.