How to Convert a Map to JSON String in JavaScript ?
A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript.
However, JSON.stringify() does not directly support Map objects.
Table of Content
- Using Object.fromEntries() Method
- Using Array Spread and Reduce
- Handling Nested Maps
Using Object.fromEntries() Method
One of the simplest ways to convert a Map to JSON is to first convert the Map to an object using Object.fromEntries() and then stringify the object.
Example: This example shows the use of the above-explained approach.
const map = new Map([
['name', 'Beginner'],
['contact', '+91-9876543210'],
['city', 'noida']
]);
const obj = Object.fromEntries(map);
const json = JSON.stringify(obj);
console.log(json);
Output
{"name":"Beginner","contact":"+91-9876543210","city":"noida"}
Using Array Spread and Reduce
We can use a combination of array spread and reduce() to convert the Map to an object, and then stringify it.
Example: This example shows the use of the above-explained approach.
const map = new Map([
['name', 'Beginner'],
['contact', '+91-9876543210'],
['city', 'noida']
]);
const obj = [...map].reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
const json = JSON.stringify(obj);
console.log(json);
Output
{"name":"Beginner","contact":"+91-9876543210","city":"noida"}
Handling Nested Maps
If your Map contains other Maps as values, you can use a recursive function to convert it to JSON.
Example: In this example, the nestedMap contains a nested Map under the key ‘Address’. The mapToJson function successfully converts this structure into a JSON string, which is printed to the console.
function mapToJson(map) {
const obj = {};
for (const [key, value] of map) {
obj[key] = value instanceof Map ? mapToJson(value) : value;
}
return JSON.stringify(obj);
}
const nestedMap = new Map([
['name', 'Beginner'],
['Address', new Map([
['sector', '136'],
['mobile', '+91-9876543210']
])],
['city', 'noida']
]);
const json = mapToJson(nestedMap);
console.log(json);
Output
{"name":"Beginner","Address":"{\"sector\":\"136\",\"mobile\":\"+91-9876543210\"}","city":"noida"}
Contact Us