JavaScript中json对象序列化转换



jquery实现方法是:
window.JSON && window.JSON.parse ?window.JSON.parse( data ):(new Function("return " + data))();
ext,dojo实现方法是:
eval("(" + json + ")"); // Object

比较好的方式:
JSON = {
useHasOwn: ({}.hasOwnProperty ? true: false),
pad: function(n) {
return n < 10 ? "0" + n: n;
},
m: {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"': '\\"',
"\\": '\\\\'
},
encodeString: function(s) {
if (/["\\\x00-\x1f]/.test(s)) {
return '"' + s.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 '"' + s + '"';
},
encodeArray: function(o) {
var a = ["["],b, i, l = o.length,v;
for (i = 0; i < l; i += 1) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(v === null ? "null": this.encode(v));
b = true;
}
}
a.push("]");
return a.join("");
},
encodeDate: function(o) {
return '"' + o.getFullYear() + "-" + pad(o.getMonth() + 1) + "-" + pad(o.getDate()) + "T" + pad(o.getHours()) + ":" + pad(o.getMinutes()) + ":" + pad(o.getSeconds()) + '"';},
encode: function(o) {
if (typeof o == "undefined" || o === null) {
return "null";
} else if (o instanceof Array) {
return this.encodeArray(o);
} else if (o instanceof Date) {
return this.encodeDate(o);
} else if (typeof o == "string") {
return this.encodeString(o);
} else if (typeof o == "number") {
return isFinite(o) ? String(o) : "null";
} else if (typeof o == "boolean") {
return String(o);
} else {
var self = this;
var a = ["{"],b,i,v;
for (i in o) {
if (!this.useHasOwn || o.hasOwnProperty(i)) {
v = o[i];
switch (typeof v) {
case "undefined":
case "function":
case "unknown":
break;
default:
if (b) {
a.push(',');
}
a.push(self.encode(i), ":", v === null ? "null": self.encode(v));
b = true;
}
}
}
a.push("}");
return a.join("");
}
},
decode: function(json) {
return eval("(" + json + ')');
}
};


[color=blue]JSON.decode('{a:1}')
JSON.encode({a:1,b:{c:'2'}})[/color]

参考:
[url]http://www.ramirezcobos.com/2009/12/30/json-jquery-plugin/[/url]
[url]http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值