Skip to content

Instantly share code, notes, and snippets.

@paambaati
Last active January 16, 2019 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paambaati/99d6a55e27601b64085f56c2740b1c7d to your computer and use it in GitHub Desktop.
Save paambaati/99d6a55e27601b64085f56c2740b1c7d to your computer and use it in GitHub Desktop.
JSON stringifier that handles ES6 Maps
// Optional: If any dependency is overriding Map's toJSON function,
// you might want to reset it.
// Why? See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior
delete Map.prototype.toJSON;
function customStringifier(key, value) {
if (value instanceof Map) {
// Convert Maps to JSON objects.
let obj = Object.create(null);
for (let [k, v] of value) {
obj[k] = v;
}
return obj;
} else {
return value;
}
}
const fixture = {
"a": 1,
"b": "c",
"d": true,
"e": new Map([["lol", "haha"], ["zero", 123], ["yes", false]]),
};
console.log(JSON.stringify(fixture, customStringifier));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment