日期:2014-05-16 浏览次数:20406 次
//JSON对象和String对象转化 Ext.util.JSON = { //格式化数字<10的前面补0 pad : function(n) { return n < 10 ? "0" + n : n; }, //把字符串转化为JSON格式 decode:function(json){ return eval("(" + json + ')'); }, //把JSON对象转化为字符串 encode:function(o){ if(typeof o == "undefined" || o === null){ return "null"; }else if(Ext.isArray(o)){//数组 var a = ["["], b, i, l = o.length, v; for (i = 0; i < l; i++) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if (b) { a.push(','); } a.push(v === null ? "null" : Ext.util.JSON.encode(v)); b = true; } } a.push("]"); return a.join(""); }else if(Ext.isDate(o)){//日期对象 return '"' + o.getFullYear() + "-" + Ext.util.JSON.pad(o.getMonth() + 1) + "-" + Ext.util.JSON.pad(o.getDate()) + " " + Ext.util.JSON.pad(o.getHours()) + ":" + Ext.util.JSON.pad(o.getMinutes()) + ":" + Ext.util.JSON.pad(o.getSeconds()) + '"'; }else if(typeof o == "string"){//字符串,转义回车换行,双引号,反斜杠...等 var m = { "\b": '\\b', "\t": '\\t', "\n": '\\n', "\f": '\\f', "\r": '\\r', '"' : '\\"', "\\": '\\\\' }; if (/["\\\x00-\x1f]/.test(o)) { return '"' + o.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if(c){ return c; } c = b.charCodeAt(); return "\\u00" + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"'; } return '"' + o + '"'; }else if(typeof o == "number"){ return isFinite(o) ? String(o) : "null"; }else if(typeof o == "boolean"){ return String(o); }else {//json格式的对象 var a = ["{"], b, i, v; for (i in o) { v = o[i]; switch (typeof v) { case "undefined": case "function": case "unknown": break; default: if(b){ a.push(','); } a.push(Ext.util.JSON.encode(i), ":", v === null ? "null" : Ext.util.JSON.encode(v)); b = true; } } a.push("}"); return a.join(""); } } }; Ext.encode = Ext.util.encode; Ext.decode = Ext.util.decode;