How to Convert Map to JSON in JavaScript ?
Last Updated :
18 Apr, 2024
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.
Similar Reads
How to Convert a Map to JSON String in JavaScript ? 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. Table of ContentUsing Object.fromEntries() MethodUsing A
2 min read
How to Convert XML to JSON in JavaScript? To convert XML to JSON in JavaScript, various methods and libraries and be used. Here, we use xml-js library that provides xml2json function to convert XML to JSON data. It takes XML data as input and gives the JSON objects as output. We can also use the DOMParser from the xmldom package to convert
2 min read
How to Convert CSV to JSON in JavaScript ? In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in J
3 min read
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 HTML to JSON in JavaScript ? Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json Lib
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 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 JSON Object to CSV in JavaScript ? JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Conte
3 min read
How to Convert Blob Data to JSON in JavaScript ? When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use t
2 min read
How To Convert Map Keys to an Array in JavaScript? Here are the various methods to convert Map keys to an array in JavaScript1. Using array.from() MethodThe Array.from() method in JavaScript converts Map keys to an array by using 'Array.from(map.keys())'. JavaScriptlet map = new Map().set('GFG', 1).set('Geeks', 2); let a = Array.from(map.keys()); co
2 min read