Skip to content

Instantly share code, notes, and snippets.

@sidouglas
Created December 24, 2020 06:14
Show Gist options
  • Save sidouglas/ca95965d0e4b36069841b60c7e739dca to your computer and use it in GitHub Desktop.
Save sidouglas/ca95965d0e4b36069841b60c7e739dca to your computer and use it in GitHub Desktop.
safe jsonStringify
/**
* 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