Skip to content

Instantly share code, notes, and snippets.

@benavern
Created April 8, 2020 09:27
Show Gist options
  • Save benavern/e60b31155ea0c363edf2e3bbd4de2ea2 to your computer and use it in GitHub Desktop.
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
/**
* 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