Skip to content

Instantly share code, notes, and snippets.

@zmmbreeze
Created March 7, 2014 09:13
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save zmmbreeze/9408172 to your computer and use it in GitHub Desktop.
Save zmmbreeze/9408172 to your computer and use it in GitHub Desktop.
json stringify can deal with circular reference
// 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
@lzambarda
Copy link

This can now be implemented with latest javascript API too.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value

@boussou
Copy link

boussou commented Apr 5, 2019

It is the same right?

@boussou
Copy link

boussou commented Apr 5, 2019

why not wrapping it in a function like I did in this fork:
https://gist.github.com/boussou/ca738c68b1850115e314979a8ae69b58

@wkrueger
Copy link

wkrueger commented Aug 7, 2019

this is plain wrong. The multiple ocurrence of the same reference in the same structure does not necessarily implies circularity. You'd have to do something recursive.

var x = {}
var a = {
  b: x,
  c: x
}

@saitonakamura
Copy link

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

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