<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Showing how a Javascript Map can be JSON formatted</h1>
<p>
By default, <pre>JSON.stringify(new Map([['aKey','aKeyValue', 'bKey', 'bKeyValue']]));</pre>
doesn't work. The result is just <pre>{}</pre> This Plunker shows how to make it work.
</p>
<div id="results">
Results are:<br>
</div>
<script src="script.js"></script>
</body>
</html>
// when running in the browser show the results in the page
// when running in NodeJS show results on console
if (typeof document === 'undefined'){
var document = {};
printResults = console.log;
} else {
printResults = function (msg){
let node = document.createElement("pre");
let theText = document.createTextNode(msg);
node.appendChild(theText);
document.getElementById("results").appendChild(node);
}
}
var aMap = new Map([['aKey','aKeyValue'], ['bKey', 'bKeyValue']]);
// Output: JSON of a map results in {}
// Based on code from http://2ality.com/2015/08/es6-map-json.html
function mapToObject(aMap) {
let obj = Object.create(null);
for (let [k,v] of aMap) {
// We don’t escape the key '__proto__' which can cause problems on older engines
if (v instanceof Map) {
obj[k.toString()] = mapToObject(v); // handle Maps that have Maps as values
} else {
obj[k.toString()] = v; // calling toString handles case where map key is not a string JSON requires key to be a string
}
}
return obj;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
// from http://www.dyn-web.com/tutorials/php-js/json/filter.php
// example replacer function
function replacer(name, val) {
//console.log('replacer name=' + name + ' value ' + val);
if (val instanceof Map){
// Convert Map to Object
return mapToObject(val);
} else {
return val; // return as is
}
}
function myJsonStringify(obj){
let rtn;
if (obj instanceof Map) {
rtn = JSON.stringify(mapToObject(obj), replacer, 4);
} else {
rtn = JSON.stringify(obj, replacer, 4);
}
return rtn;
}
// passing replacer and indent to stringify
printResults("JSON.stringify (default) of aMap returns " + JSON.stringify(aMap, null, 4));
printResults("JSON.stringify (with replacer) returns " + JSON.stringify(aMap, replacer, 4));
printResults("myJsonStringify of aMap returns " + myJsonStringify(aMap));
// If you have a known javascript object (most likely the case then) you can just use JSON.stringify()
let anObj = { somekey: 'someValue', 'keyForMapValue': aMap };
printResults("JSON.stringify of anObj returns " + JSON.stringify(anObj, replacer, 4));
// It also supports nested maps
// If you have a known javascript object (most likely the case then) you can just use JSON.stringify()
let anObjWithNestedMap = { somekey: 'someValue', 'keyForMapValue': aMap, nestedMap: new Map(aMap) };
printResults("JSON.stringify of anObjWithNestedMap " + JSON.stringify(anObjWithNestedMap, replacer, 4));
/* Styles go here */
# This example shows how to using JSON.stringify() on Javascript Map objects
By default, JSON.stringify() doesn't work on Map objects.
The question is asked at [https://stackoverflow.com/questions/29085197/how-do-you-json-stringify-an-es6-map] and some answer that this is not possible.
This code shows that it is possible and how to do it.
You can take this source and run it in NodeJS or in the browser.
It uses console.log() so it can work in either.