Skip to content

Instantly share code, notes, and snippets.

@radi-cho
Created May 6, 2020 09:17
Show Gist options
  • Save radi-cho/6ac02ad1bfd2b98b9009f3ba84afa4bd to your computer and use it in GitHub Desktop.
Save radi-cho/6ac02ad1bfd2b98b9009f3ba84afa4bd to your computer and use it in GitHub Desktop.
JSON.safeStringify method
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