-
-
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
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 | |
//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