Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created September 20, 2021 11:11
Show Gist options
  • Save fostyfost/94eff7b8d562a918e7945902c3f7fb99 to your computer and use it in GitHub Desktop.
Save fostyfost/94eff7b8d562a918e7945902c3f7fb99 to your computer and use it in GitHub Desktop.
Converting circular structure to JSON
function censor(censor: any) {
let i = 0
return function(_: any, value: unknown) {
if (i !== 0 && typeof censor === 'object' && typeof value === 'object' && censor === value) {
return '[Circular]'
}
// seems to be a harded maximum of 11 serialized objects?
if (i >= 10) {
return '[Unknown]'
}
++i // so we know we aren't using the original object anymore
return value
}
}
JSON.stringify(obj, censor(obj))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment