How to Convert JSON to/From a Map in JavaScript

Last updated on October 15, 2022
How to Convert JSON to/From a Map in JavaScript

To convert JSON to a Map in JavaScript:

  1. Parse the JSON string to an object with the JSON.parse() method.
  2. Call Object.entries() with this object as an argument.
  3. Pass the result of Object.entries() to the Map() constructor.

For example:

const json =
  '{"user1":"John","user2":"Kate","user3":"Peter"}';

const map = new Map(Object.entries(JSON.parse(json)));

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

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.

Convert Map to JSON

To convert the Map back to a JSON string, call the Object.fromEntries() method with the Map as an argument, and pass the result to the JSON.stringify() method:

const json =
  '{"user1":"John","user2":"Kate","user3":"Peter"}';

const map = new Map(Object.entries(JSON.parse(json)));

const jsonFromMap = JSON.stringify(Object.fromEntries(map));

// {"user1":"John","user2":"Kate","user3":"Peter"}
console.log(jsonFromMap);

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);
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