How to Convert a Map to JSON String in JavaScript ?
Last Updated :
27 Jun, 2024
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.
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.
JavaScript
const map = new Map([
['name', 'Geeks'],
['contact', '+91-9876543210'],
['city', 'noida']
]);
const obj = Object.fromEntries(map);
const json = JSON.stringify(obj);
console.log(json);
Output{"name":"Geeks","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.
JavaScript
const map = new Map([
['name', 'Geeks'],
['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":"Geeks","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.
JavaScript
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', 'Geeks'],
['Address', new Map([
['sector', '136'],
['mobile', '+91-9876543210']
])],
['city', 'noida']
]);
const json = mapToJson(nestedMap);
console.log(json);
Output{"name":"Geeks","Address":"{\"sector\":\"136\",\"mobile\":\"+91-9876543210\"}","city":"noida"}
Using Array.from() and Reduce
This method uses Array.from() to convert the Map into an array of key-value pairs, and then reduces the array into an object, which can then be stringified into JSON.
Example: This example demonstrates the use of Array.from() and reduce() to convert a Map to a JSON string.
JavaScript
const map = new Map([
['name', 'Geeks'],
['contact', '+91-9876543210'],
['city', 'noida']
]);
const obj = Array.from(map).reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
const json = JSON.stringify(obj);
console.log(json);
Output{"name":"Geeks","contact":"+91-9876543210","city":"noida"}