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"}
Similar Reads
How to Convert JSON to string in JavaScript ? In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission.Several methods can be used
3 min read
How to Convert String to JSON in JavaScript? In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Us
2 min read
How To Convert Base64 to JSON String in JavaScript? There could be situations in web applications, where there is a need to decode the data from Base64 format back into its original JSON format. It generally happens when one has to transmit data over the network where Base64 encoding is well suited for encoding binary data.In this article, we will se
2 min read
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 convert
3 min read
How to convert a Set to Map in JavaScript? A Set is a collection of unique values. It stores only the data in the form of values while a Map can store the data in the form of key-value pairs. These are the different ways of converting a Set to a Map in JavaScript: Table of Content Using the Array.from() methodUsing the Spread Operator with m
3 min read
How to Convert String of Objects to Array in JavaScript ? This article will show you how to convert a string of objects to an array in JavaScript. You have a string representing objects, and you need to convert it into an actual array of objects for further processing. This is a common scenario when dealing with JSON data received from a server or stored i
3 min read
How to Convert JSON to base64 in JavaScript ? Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a
2 min read
How to Create JSON String in JavaScript? JSON strings are widely used for data interchange between a server and a client, or between different parts of a software system. So converting objects to JSON strings is very important for good client-server communication. Below are the following approaches to creating a JSON string: Table of Conte
2 min read
How to Convert JSON to Blob in JavaScript ? This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light
2 min read
How to Convert JS Object to JSON String in JQuery/Javascript? Converting a JavaScript object to a JSON string means using the JSON.stringify() method to transform the object into a JSON-formatted string. This allows for efficient data storage, transmission, and debugging by representing complex data structures in a standardized text format.To Convert JS Object
4 min read