Skip to content

Instantly share code, notes, and snippets.

@mrfolkblues
Created April 8, 2022 21:11
Show Gist options
  • Save mrfolkblues/27858032aa890255560413e0840b3259 to your computer and use it in GitHub Desktop.
Save mrfolkblues/27858032aa890255560413e0840b3259 to your computer and use it in GitHub Desktop.
JSON stringify that safely handles circular references (found on StackOverflow somewhere)
// safely handles circular references
JSON.safeStringify = (obj, indent = 2) => {
let cache = []
const retVal = JSON.stringify(
obj,
(key, value) =>
typeof value === 'object' && value !== null
? cache.includes(value)
? undefined // Duplicate reference found, discard key
: cache.push(value) && value // Store value in our collection
: value,
indent
)
cache = null
return retVal
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment