Skip to main content

How to Convert a Map to and from JSON in JavaScript

When you need to serialize data for storage or for sending in an API request, you'll often use JSON (JavaScript Object Notation). However, a standard JavaScript Map object does not serialize correctly with JSON.stringify(), which can lead to unexpected empty objects and data loss.

This guide will explain why this happens and teach you the modern, standard methods for correctly converting a Map to a JSON string and parsing it back into a Map.

The Core Problem: Why JSON.stringify() Fails on a Map

The JSON.stringify() method is designed to work with plain JavaScript objects, arrays, and primitive values. A Map is a complex, iterable object with an internal structure that JSON does not understand. When you try to stringify a Map directly, you get an empty object.

Example of code with error:

const myMap = new Map([
['name', 'Alice'],
['age', 30],
]);

// ⛔️ This does NOT work as expected!
const json = JSON.stringify(myMap);

console.log(json); // Output: "{}" (An empty object, data is lost)

To solve this, we must first convert the Map into a plain object, which JSON.stringify() can correctly process.

Part 1: How to Convert a Map to a JSON String

The solution is a simple two-step process: Map -> Plain Object -> JSON String.

The logic:

  1. Object.fromEntries(map): This modern method is designed for this exact task. It takes an iterable of [key, value] pairs (which a Map is) and converts it into a new plain object.
  2. JSON.stringify(object): Now that you have a plain object, you can safely stringify it to JSON.

Recommended Solution:

const myMap = new Map([
['name', 'Alice'],
['age', 30],
]);

// Step 1: Convert the Map to a plain object
const obj = Object.fromEntries(myMap);
console.log('Plain Object:', obj); // Output: { name: 'Alice', age: 30 }

// Step 2: Stringify the plain object
const json = JSON.stringify(obj);
console.log('JSON String:', json); // Output: '{"name":"Alice","age":30}'

Output:

Plain Object: {name: 'Alice', age: 30}
JSON String: {"name":"Alice","age":30}
note

This can be written as a concise one-liner:

const json = JSON.stringify(Object.fromEntries(myMap));

Part 2: How to Convert a JSON String back to a Map

The inverse operation is also a two-step process: JSON String -> Plain Object -> Map.

The logic:

  1. JSON.parse(json): This standard method parses a JSON string, producing a plain JavaScript object.
  2. Object.entries(object): This method does the opposite of fromEntries. It takes a plain object and returns an array of its [key, value] pairs.
  3. new Map(entries): The Map constructor can accept an array of key-value pairs to create a new Map.

Recommended Solution:

const json = '{"name":"Alice","age":30}';

// Step 1: Parse the JSON string to a plain object
const obj = JSON.parse(json);
console.log('Parsed Object:', obj); // Output: { name: 'Alice', age: 30 }

// Step 2: Convert the object's entries into a Map
const myMap = new Map(Object.entries(obj));
console.log('Final Map:', myMap); // Output: Map(2) { 'name' => 'Alice', 'age' => 30 }

Output:

Parsed Object: {name: 'Alice', age: 30}
Final Map: Map(2) {'name' => 'Alice', 'age' => 30}
note

This can also be written as a one-liner:

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

Reusable Functions (Best Practice)

For cleaner and more maintainable code, it's a great practice to encapsulate this logic in reusable helper functions.

function mapToJson(map) {
return JSON.stringify(Object.fromEntries(map));
}

function jsonToMap(jsonStr) {
return new Map(Object.entries(JSON.parse(jsonStr)));
}

// --- Round-trip Example ---
const originalMap = new Map([['id', 1], ['status', 'active']]);

// 1. Convert to JSON
const json = mapToJson(originalMap);
console.log('Serialized to JSON:', json);

// 2. Convert back to a Map
const finalMap = jsonToMap(json);
console.log('Deserialized to Map:', finalMap);

console.log(finalMap.get('status'));

Output:

Serialized to JSON: {"id":1,"status":"active"}
Deserialized to Map: Map(2) {'id' => 1, 'status' => 'active'}
active

Conclusion

Directly serializing a Map to JSON is a common pitfall in JavaScript. The key is to use a plain object as an intermediate step.

  • To convert a Map to JSON, use JSON.stringify(Object.fromEntries(map)).
  • To convert JSON back to a Map, use new Map(Object.entries(JSON.parse(json))).

By using these modern and idiomatic methods, you can reliably serialize and deserialize Map objects for storage or data transmission.