简单的json串生成
浏览量:3471
最近,在一个web项目中需要通过json数据作为传递。尝试了几个json的生成插件,感觉都不太理想。于是,自己动手,尝试着写了一段生成json的代码。大家如有兴趣,可以扩展下O(∩_∩)O哈!
(function($) {
$.extend({
//create Json
toJson: function(obj) {
if(obj==undefined ||obj.length==0)
{
return"";
}
varvalue;
varj = "{";
varflag = false;
for(vark inobj) {
value = obj[k];
if(typeof(value) == "string") {
j += "\"" + k + "\"" + ":" + "\"" + value + "\"" + ",";
flag = true;
} elseif(typeof(value) == "number") {
j += "\"" + k + "\"" + ":" + value + ",";
flag = true;
} elseif(typeof(value) == "object") {
if(Object.prototype.toString.apply(value) == "[object Array]") {
varindex = 0;
varsub = "\"" + k + "\"" + ":[";
for(index = 0; index < value.length; ++index) {
sub += $.toJson(value[index]) + ",";
}
if(index===0)
{
j+=sub+"],";
}
else
{
j += sub.substring(0, sub.length - 1) + "],";
}
flag = true;
}
}
}
if(flag) {
j = j.substring(0, j.length - 1) + "}";
}
returnj;
}
}
});
})(jQuery);