Handle cyclic object error
Handle "TypeError: cyclic object value" when JSON.stringify(object)
JavaScript
obj = {
x: 555,
y: "hi"
}
obj.myself = obj
var jsonify = function(obj){
var seen = [];
var json = JSON.stringify(obj, function(key, value){
if (typeof value === 'object') {
if ( !seen.indexOf(value) ) {
return '__cycle__' + (typeof value) + '[' + key + ']';
}
seen.push(value);
}
return value;
}, 4);
return json;
};
alert(jsonify(obj));