Created
April 8, 2020 09:27
-
-
Save benavern/e60b31155ea0c363edf2e3bbd4de2ea2 to your computer and use it in GitHub Desktop.
a JSON.stringify replacer that prevents from circular structures & un-stringify-able properties
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
/** | |
* Creates a formatter for JSON.stringify that prevents from circular structures and not stringify-able values | |
*/ | |
function safeJsonReplacer() { | |
const seen = new Set(); | |
return (key, val) => { | |
// prevent from circular structures | |
if (typeof val === 'object' && val !== null) { | |
if (seen.has(val)) return; | |
seen.add(val); | |
} | |
let formattedVal; | |
if (val && [String, Number, Array, Object].includes(val.constructor)) { // return as-is if it is a safe value | |
formattedVal = val; | |
} else { // try to format if it is a dangerous value | |
try { | |
formattedVal = val.toString(); | |
} catch (e) { | |
formattedVal = undefined; | |
} | |
} | |
return formattedVal; | |
}; | |
} | |
console.log(JSON.stringify('string', safeJsonReplacer(), 2)) | |
console.log(JSON.stringify(2, safeJsonReplacer(), 2)) | |
console.log(JSON.stringify(["coucou", 1, 2, null, undefined], safeJsonReplacer(), 2)) | |
console.log(JSON.stringify(global, safeJsonReplacer(), 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment