Skip to content

Instantly share code, notes, and snippets.

@boussou
Forked from zmmbreeze/stringify.js
Last active October 8, 2020 20:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boussou/ca738c68b1850115e314979a8ae69b58 to your computer and use it in GitHub Desktop.
Save boussou/ca738c68b1850115e314979a8ae69b58 to your computer and use it in GitHub Desktop.
Converting circular structure to JSON on JSON.stringify / this is a version of the solution for Vue.js
// http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json/11616993#11616993
//this is a version for Vue.js
//filters vue.js internal properties
//you can extend Vue object instead
Object.stringify = function(value, space) {
var cache = [];
var output = JSON.stringify(value, function (key, value) {
//filters vue.js internal properties
if(key && key.length>0 && (key.charAt(0)=="$" || key.charAt(0)=="_")) {
return;
}
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;
}, space)
cache = null; // Enable garbage collection
return output;
}
//---------------------------------
var o = {};
o.o = o;
var demo = new Vue({
el: '#el',
data: {a:1, b:"s"},
methods: {}
});
console.log( Object.stringify(demo,2));
console.log( Object.stringify(o));
//---------------------------------
//same code, 2nd option --> in prototype
Object.prototype.stringify= function(space) {
var cache = [];
var output = JSON.stringify(this, function (key, value) {
//filters vue.js internal properties
if(key && key.length>0 && (key.charAt(0)=="$" || key.charAt(0)=="_")) {
return;
}
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;
}, space)
cache = null; // Enable garbage collection
return output;
}
//---------------------------------
console.log( demo.stringify());
console.log( o.stringify());
console.log( demo.stringify(2)); //indentation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment