Open In App

How to Convert Map to JSON in JavaScript ?

In JavaScript, when working with data, you might encounter situations where you need to convert a Map object into a JSON format. This can be useful for sending data over the network, storing data in local storage, or interfacing with APIs that expect JSON data.

Converting a Map to JSON means converting each key-value pair from the Map into a JSON object. JavaScript's built-in JSON object provides methods to perform this conversion efficiently.

Map Object

Let's start by quickly reviewing what a JavaScript Map object is. A map is a set of key-value pairings in which objects and primitive values can be included as keys, and the values can be any kind of data.

Using Object.fromEntries and JSON.stringify

This method involves converting the Map into an array of key-value pairs using Array.from() or spreading (...) the Map, then using Object.fromEntries() to convert this array back into an object, followed by JSON.stringify() to convert the object to JSON.

Syntax

const mapToJson = (map) => {
return JSON.stringify(Object.fromEntries(map));
};

Explanation:

Example: Implementation to show how to convert map to JSON in JavaScript.

const mapToJson = (map) => {
    return JSON.stringify(Object.fromEntries(map));
};

const myMap = new Map([
    ['name', 'Abdullah'],
    ['age', 21],
    ['city', 'New York']
]);

const jsonString = mapToJson(myMap);
console.log(jsonString);

Output
{"name":"Abdullah","age":21,"city":"New York"}

Using Iterative Conversion

This method involves iterating through each key-value pair in the Map and constructing a new object that mirrors these pairs. This object is then converted to JSON using JSON.stringify().

Syntax

const mapToJson = (map) => {
const jsonObj = {};
map.forEach((value, key) => {
jsonObj[key] = value;
});
return JSON.stringify(jsonObj);
};

Explanation:

Example: Implementation to show how to convert map to JSON in JavaScript.

const mapToJson = (map) => {
    const jsonObj = {};
    map.forEach((value, key) => {
        jsonObj[key] = value;
    });
    return JSON.stringify(jsonObj);
};
const myMap = new Map([
    ['name', 'Abdullah'],
    ['age', 21],
    ['city', 'New York']
]);

const jsonString = mapToJson(myMap);
console.log(jsonString);

Output
{"name":"Abdullah","age":21,"city":"New York"}

Note: This JSON string can then be parsed back into a JavaScript object using JSON.parse() if needed.

Use Cases

Conclusion

Converting a Map to JSON in JavaScript is a common task that can be accomplished using built-in JavaScript methods. Depending on your specific use case and data structure, you can choose between the direct approach using Object.fromEntries() or the iterative approach to create a JSON representation of your Map object. These techniques are fundamental for working with JSON data in JavaScript applications.

Article Tags :