Skip to content

Instantly share code, notes, and snippets.

@slimlime
Forked from zmmbreeze/stringify.js
Created July 9, 2018 05:30
Show Gist options
  • Select an option

  • Save slimlime/c7ad08a6fa2914f996bd68fe8e6a2ce2 to your computer and use it in GitHub Desktop.

Select an option

Save slimlime/c7ad08a6fa2914f996bd68fe8e6a2ce2 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment