Created
March 7, 2014 09:13
-
-
Save zmmbreeze/9408172 to your computer and use it in GitHub Desktop.
json stringify can deal with circular reference
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
// http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json/11616993#11616993 | |
var o = {}; | |
o.o = o; | |
var cache = []; | |
JSON.stringify(o, 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
yeah, it has this bug with having the same object in a different branches
you can use my version which addresses this
https://gist.github.com/saitonakamura/d51aa672c929e35cc81fa5a0e31f12a9