How to convert a Map to JSON in JavaScript

Last updated on August 10, 2023
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:

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:

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:

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:

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.

Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also