Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Created September 15, 2012 02:38
Show Gist options
  • Save chrisirhc/3726139 to your computer and use it in GitHub Desktop.
Save chrisirhc/3726139 to your computer and use it in GitHub Desktop.
Safe JSON stringify
// A JSON stringifier that handles cycles safely.
// Usage: JSON.stringify(obj, safeCycles())
function safeCycles() {
var seen = [];
return function(key, val) {
if (!val || typeof val !== 'object') {
return val;
}
// Watch out for Window host objects that are trickier to handle.
if (val instanceof Window || seen.indexOf(val) !== -1) {
return '[Circular]';
}
seen.push(val);
return val;
};
}
@chrisirhc
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment