Converting a Map to a JSON string
In modern JavaScript (ES6 and beyond), the most elegant and efficient way to convert a Map to JSON is to use the Object.fromEntries()
method to convert the Map to an object and then use the JSON.stringify()
method to convert that object to a JSON string. In general, the syntax will look like this:
const json = JSON.stringify(Object.fromEntries(map));
Example:
const map = new Map([
['website', 'Sling Academy'],
['age', 10],
]);
const json = JSON.stringify(Object.fromEntries(map));
console.log(json);
Output:
{"website":"Sling Academy","age":10}
A common real-world use case of converting a JavaScript Map to JSON is when you want to serialize the Map and send it over the network or store it in a file. JSON is a widely used format for data interchange and storage, and it can be easily parsed by most languages and platforms.
Convert JSON string to a Map
If you are given a JSON string and your job is to turn it into a Map, you can use the JSON.parse()
method to parse the JSON string into an object, and then use the Object.entries()
method to get an array of key-value pairs. Then, call the Map()
constructor with the array of key-value pairs.
The general syntax for this task will look as follows (most of the time):
const map = new Map(Object.entries(JSON.parse(json)));
Example:
const json = '{"name":"Wolf","age":99, "city": "The Land of Wolves"}';
const obj = JSON.parse(json);
const map = new Map(Object.entries(obj));
console.log(map);
Output:
Map(3) {
'name' => 'Wolf',
'age' => 99,
'city' => 'The Land of Wolves'
}
One possible use case of converting a JSON string into a Map in JavaScript is when you want to deserialize the JSON and access the data as key-value pairs. Map is a built-in object that allows you to store and retrieve data using any value as a key, unlike plain objects that only accept strings or symbols as keys.