Skip to content

Instantly share code, notes, and snippets.

@boussou boussou/stringify.js forked from zmmbreeze/stringify.js
Last active Apr 5, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.