Created
December 24, 2020 06:14
-
-
Save sidouglas/ca95965d0e4b36069841b60c7e739dca to your computer and use it in GitHub Desktop.
safe jsonStringify
This file contains hidden or 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
/** | |
* jsonStringify | |
* Output any data structure to a string, without circular dep issues | |
* @param {*} data data to stringify | |
* @param {Number} space - indentation level | |
* @return {string} | |
*/ | |
export function jsonStringify (data, space = 2) { | |
const getCircularReplacer = () => { | |
const seen = new WeakSet() | |
return (key, value) => { | |
if (typeof value === 'object' && value !== null) { | |
if (seen.has(value)) { | |
return | |
} | |
seen.add(value) | |
} | |
return value | |
} | |
} | |
return JSON.stringify(data, getCircularReplacer(), space) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment