JSON stringifier that handles ES6 Maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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