Open In App

How to Convert Map to JSON in JavaScript ?

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • We create a function mapToJson that takes a Map as an argument.
  • Object.fromEntries(map) converts the Map into an array of key-value pairs and then into a plain object.
  • JSON.stringify() converts this plain object into a JSON string.

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

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:

  • We create a function mapToJson that takes a Map as an argument.
  • We initialize an empty JavaScript object jsonObj.
  • We iterate through each key-value pair in the Map using map.forEach(), and for each pair, we assign the key-value to jsonObj.
  • Finally, we use JSON.stringify() to convert jsonObj into a JSON string.

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

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

  • Nested Structures: If your Map contains nested structures or objects as values, ensure that those nested structures can be serialized to JSON.
  • Performance: Both methods are efficient, but the iterative method (forEach()) might be more suitable if you need to perform additional transformations or validations during the conversion process.
  • Compatibility: These methods work in all modern browsers and Node.js environments.

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads