Skip to content

Instantly share code, notes, and snippets.

@pkrnjevic
Last active June 12, 2017 19:18
Show Gist options
  • Save pkrnjevic/1aedde9815d44059d0fcb1110e65dab8 to your computer and use it in GitHub Desktop.
Save pkrnjevic/1aedde9815d44059d0fcb1110e65dab8 to your computer and use it in GitHub Desktop.
Gist showing how to JSON.stringify objects with circular references. Useful when dumping Express requests or dom.
// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(req, 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;
});
cache = null; // Enable garbage collection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment