注册|登录

联系电话:024-31891684  13390130939
沈阳软件公司--沈阳软件定制

沈阳软件开发_沈阳软件公司_沈阳软件定制/软件/最新技术

Latest technology最新技术

简单的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);

沈阳团购网|营口网站制作|沈阳软件公司|软件定制|网站建设|加盟易势|提交问题