How to convert a Map to JSON in JavaScript

To convert a Map to JSON in JavaScript, call the Object.fromEntries(map), then pass the result to the JSON.stringify() method.

For example:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const json = JSON.stringify(Object.fromEntries(map)); // {"user1":"John","user2":"Kate","user3":"Peter"} console.log(json);

We first transform the Map with Object.fromEntries(), because we can’t serialize a Map to a JSON string directly. The Object.fromEntries() method transforms any list of key-value pairs into an object:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const obj = Object.fromEntries(map); // { user1: 'John', user2: 'Kate', user3: 'Peter' } console.log(obj);

Convert JSON back to Map

To convert the JSON string back to a Map:

  1. Parse the JSON string to an object with JSON.parse().
  2. Call Object.entries() with this object as an argument.
  3. Create a new Map object, passing the result of Object.entries() to the constructor.

For example:

JavaScript
const map = new Map([ ['user1', 'John'], ['user2', 'Kate'], ['user3', 'Peter'], ]); const jsonFromMap = JSON.stringify(Object.fromEntries(map)); const obj = JSON.parse(jsonFromMap); const mapFromObj = new Map(Object.entries(obj)); // Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' } console.log(mapFromObj);

We first convert the string to an object and then to an array, because we can’t parse a JSON string to a Map directly. The Object.entries() method takes an object and returns a list of key-value pairs that correspond to the key and value of each property of the object:

JavaScript
const obj = { user1: 'John', user2: 'Kate', user3: 'Peter', }; const arr = Object.entries(obj); // [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ] console.log(arr);

The Map() constructor can take an iterable of key-value pairs to create the Map elements, so we pass the result of the Object.entries() directly to it.



Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *