recursive object stringify
by Gerald Gillespie
JavaScript
var x='';
function ObjToSource(o,x){
if (!o) return 'null';
if (typeof(o) == "object") {
if (!ObjToSource.check) ObjToSource.check = new Array();
for (var i=0, k=ObjToSource.check.length ; i<k ; ++i) {
if (ObjToSource.check[i] == o) {return x+'{}';}
}
ObjToSource.check.push(o);
}
var k="",na=typeof(o.length)=="undefined"?1:0,str="";
for(var p in o){
if (na) k = "'"+p+ "':";
if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
else if (typeof o[p] == "object") str += k +x + ObjToSource(o[p],x+=' ')+",";
else str += k + o[p] + ",";
}
if (typeof(o) == "object"){
ObjToSource.check.pop();
x+=' ';
}
if (na) x.substring(x.length-1);
if (na) return "\n"+x+"{"+str.slice(0,-1)+x+"}\n";
else return "\n"+x+"["+str.slice(0,-1)+"]";
}
var wtf =function(){ return 1;}
var O = { a: 1, b: 2,
c: { c1: 3, c2: 4,
c3: { t: true, f: { n : false} }
},
d: { t: wtf, f: { n : {}} }
};
var z = ObjToSource(O,'');//.join('\n');
console.log(z);