Open In App

How to Convert a Map to JSON String in JavaScript ?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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"}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads