JavaScript – Convert Map to JSON String
To convert a map to JSON string in JavaScript, convert map to JavaScript object using Object.fromEntries() and then pass this object as argument to JSON.stringify() method.
Syntax
A quick syntax to convert a Map map
into JSON String is
</>
Copy
var obj = Object.fromEntries(map);
var jsonString = JSON.stringify(obj);
Examples
In the following example, we take a Map map
and convert this Map to JSON string using Object.fromEntries() and JSON.stringify() methods.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var map = new Map([
['name', 'Apple'],
['place', 'California'],
['age', 25]
]);
var obj = Object.fromEntries(map);
var jsonString = JSON.stringify(obj);
document.getElementById('output').innerHTML += jsonString;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to convert a Map into JSON string in JavaScript using JSON.stringify() method, with examples.