Skip to content

Instantly share code, notes, and snippets.

@morficus
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save morficus/7d7e9a0dcb854f7297d1 to your computer and use it in GitHub Desktop.

Select an option

Save morficus/7d7e9a0dcb854f7297d1 to your computer and use it in GitHub Desktop.
Custom replacer for JSON.stringify, specifically for handling circular references
//src: http://stackoverflow.com/a/11616993/1021300
//replace this empty object with a references to the circular one
var objectToPrint = {};
var cache = [],
output;
output = JSON.stringify(objectToPrint, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
}, 2);
cache = null; // Enable garbage collection
console.log(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment