JSON对象转化

来源:互联网 发布:python java go技术栈 编辑:程序博客网 时间:2024/05/21 10:07

 1 (function ($) { 2     $.fn.getData = function (itemTag) { 3         var obj; 4         if (itemTag) { 5             obj = []; 6             this.find(itemTag).each(function () { 7                 obj.push($(this).getData()); 8             }); 9             return obj;10         }11         else {12             obj = {};13             this.find("input,select").each(function (i, v) {14                 if (this.name) {15                     obj[encodeURIComponent(this.name)] = encodeURIComponent($.trim($(this).val()));16                 }17             });18             return obj;19         }20     };21     $.fn.setData = function (obj) {22         if ($.isPlainObject(obj)) {23             for (var p in obj) {24                 var element = $('input[name="' + decodeURIComponent(p) + '"]' + ',select[name="' + decodeURIComponent(p) + '"]');25                 if (element.length > 0 && !$.isArray(obj[p])) {26                     element.val(decodeURIComponent(obj[p]));27                 }28             }29         }30     };31 })(jQuery);32 $.extend({33     toJSON: function (obj) {34         if ($.isPlainObject(obj)) {35             var props = [];36             for (var p in obj) {37                 var prop = obj[p];38                 var propStr = '';39                 if ($.isArray(prop)) {40                     propStr += '[';41                     var items = [];42                     $.each(prop, function (i, v) {43                         if ($.type(v) == "number" || $.type(v) == "string") {44                             items.push('"' + v + '"');45                         }46                         else {47                             items.push($.toJSON(v));48                         }49                     });50                     propStr += items.join(',') + ']';51                 }52                 else {53                     propStr += '"' + prop + '"';54                 }55                 props.push('"' + p + '":' + propStr);56             }57         }58         return '{' + props.join(',') + '}';59     }60 });

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击