Last active
June 12, 2017 19:18
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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