Skip to content

Instantly share code, notes, and snippets.

@paambaati
Last active Jan 16, 2019
Embed
What would you like to do?
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