An Alternative Method For Json.stringify()
I want an alternative method for JSON.stringify(). I am using JSON.stringify and I got error like cyclic object value. I don't know how to remove this error so I'd like to know if
Solution 1:
If won't to use stringify you can reproduce it, like this:
OBJtoString(object [,n])
accempt 2 args:
object
(needed) the object you need to log (in my release array and object is the same)n
numbero of space that indent every new line inside object aruments.varOBJtoString = function(_o,_m,_rf,_dep,_res){ _dep = [], _rf = function(obj,n,_n,_a,_k,_i,_ws,_f,_e){ if(typeof obj != "object") returnfalse; if(typeof _a === "undefined") _a = "FIRST PARENT OBJECT"; _dep.push(obj), _f = (_dep.length < 1) ? function(){} : function(_z,_x){ for(_x = 0; _x <= _dep.length; _x++){ if(obj[_z] == _dep[_x]) returntrue; } returnfalse; } _ws = ""; if(typeof n === "undefined") n = 1; if(typeof _n === "undefined") _n = n; for(_k = 0; _k <= n; _k++){ _ws += " "; } var response ="{ \n"; for(var _i in obj){ if(typeof obj[_i] !== "object"){ if(typeof obj[_i] === "string") obj[_i] = "'"+obj[_i].toString()+"'"; if(typeof obj[_i] === "boolean") obj[_i] = obj[_i].toString() + " (boolean)"; response += _ws + _i + " : " + obj[_i].toString(); response += "\n"; continue; } response += (_f(_i)) ? _ws + _i + " : "+ _a +" (prevent loop)\n" : _ws + _i + " : " + _rf(obj[_i],n+_n,_n,_a); } if(_n != n) response += _ws; return response +="} \n"; } _res = _rf(_o,_m); _dep = []; return _res; }
Uses Example:
var example = {ciao : "hellow", saluto : {ciao : "ciao", dam : true}};
example.parentObj = example;
console.log(OBJtoString(example,4));
return:
{
ciao :'hellow'saluto : {
ciao :'ciao'dam :true(boolean)
}
parentObj :FIRSTPARENTOBJECT(preventloop)
}
Other Example:
varexample= {ciao :"hellow", saluto : {ciao :"ciao", dam :true}};example.parentObj=example;example.f= {
g :example
}
console.log(OBJtoString(example,4));
Return:
{
ciao :'hellow'saluto : {
ciao :'ciao'dam :true(boolean)
}
parentObj :FIRSTPARENTOBJECT(preventloop)f : {
g :FIRSTPARENTOBJECT(preventloop)
}
}
Post a Comment for "An Alternative Method For Json.stringify()"