Skip to content

Instantly share code, notes, and snippets.

@hamzakaya
Last active April 2, 2022 15:58
Show Gist options
  • Save hamzakaya/24055adf8f5e1e4b65a0316baa1b388f to your computer and use it in GitHub Desktop.
Save hamzakaya/24055adf8f5e1e4b65a0316baa1b388f to your computer and use it in GitHub Desktop.
JSON.stringify for circular
export default function circularStringify(object, { indentation } = {}) {
if (Array.isArray(object)) {
object = object.map((element) =>
JSON.parse(JSON.stringify(element, replacer())),
)
}
return JSON.stringify(object, replacer(), indentation)
}
const replacer = () => {
const seen = new WeakSet()
return (key, value) => {
if (value !== null && typeof value === 'object') {
if (seen.has(value)) return '[Circular]'
seen.add(value)
}
return value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment