当我们前台是Json变量如果能快速转化成字符串对象,然后传递到服务端进行快速处理? 下面代码就是为了实现该功能,能直接转为字符串,后台在对字符串再次转化为实体对象进行才做。
/*Json转字符串*/
function toJSONString(obj) {
var S = [];
var J = "";
if (Object.prototype.toString.apply(obj) === "[object Array]") {
for (var i = 0; i < obj.length; i++)
S.push(toJSONString(obj[i]));
J = '[' + S.join(',') + ']';
}
else if (Object.prototype.toString.apply(obj) === "[object Date]") {
J = "new Date(" + obj.getTime() + ")";
}
else if (Object.prototype.toString.apply(obj) === "[object RegExp]" || Object.prototype.toString.apply(obj) === "[object Function]") {
J = obj.toString();
}
else if (Object.prototype.toString.apply(obj) === "[object Object]") {
for (var i in obj) {
var value = typeof (obj[i]) == "string" ? '"' + obj[i] + '"' : (typeof (obj[i]) === "object" ? toJSONString(obj[i]) : obj[i]);
value = value.toString().trim().length > 0 ? value : '""';
S.push(i + ':' + value);
}
J = '{' + S.join(',') + '}';
}
return J;
}
实例:
toJSONString(item)
转载请标注来源!