转一个自写的js对象(obj)转json字符串的函数

有些小地方需要将JavaScript的obj对象转换为json字符串来使用,又不想用js的库,转一发别人写的转换函数,亲测可用。

 console.log(Serialize(jsobj));
function Serialize(obj){
switch(obj.constructor){
case Object:
var str = "{";
for(var o in obj){
str += "\"" + o+ "\"" + ":" + Serialize(obj[o]) +",";
}
if(str.substr(str.length-1) == ",")
str = str.substr(0,str.length -1);
return str + "}";
break;
case Array:
var str = "[";
for(var o in obj){
str += Serialize(obj[o]) +",";
}
if(str.substr(str.length-1) == ",")
str = str.substr(0,str.length -1);
return str + "]";
break;
case Boolean:
return "\"" + obj.toString() + "\"";
break;
case Date:
return "\"" + obj.toString() + "\"";
break;
case Function:
break;
case Number:
return "\"" + obj.toString() + "\"";
break;
case String:
return "\"" + obj.toString() + "\"";
break;
}
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注