JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString
如下示例:
直接写的a1就是一个Json对象,a2 就是一个Json对象字符串; 通过eval函数 得到的 都是Json对象, 不管参数是对象还是 字符串.
function JTS(o){
var arr = [];
var fmt = function(s) {
if (typeof s == "object" && s != null)
return JTS(s);
return /^(string|number)$/.test(typeof s) ? "\"" + s + "\"" : s;
}
for (var i in o)
arr.push("\"" + i + "\":" + fmt(o[i]));
return "{" + arr.join(",") + "}";
}
12
//Json 对象
var a1=[{"n1":"n1t","n2":"23","n3":"1"},{"n2":"n2t","n2":"12","n3":"1"},{"n3":"n3t","n2":"64","n3":"3"},{"n4":"n4t","n2":"78","n3":"4"},{"n5":"n5t","n2":"34","n3":"1"},{"n6":"n6t","n2":"56","n3":"4"},{"n7":"n7t","n2":"2","n3":"3"},{"n8":"n8t","n2":"1","n3":"4"}];
//Json对象字符串
var a2="[{\"n1\":\"n1t\",\"n2\":\"23\",\"n3\":\"1\"},{\"n2\":\"n2t\",\"n2\":\"12\",\"n3\":\"1\"},{\"n3\":\"n3t\",\"n2\":\"64\",\"n3\":\"3\"},{\"n4\":\"n4t\",\"n2\":\"78\",\"n3\":\"4\"},{\"n5\":\"n5t\",\"n2\":\"34\",\"n3\":\"1\"},{\"n6\":\"n6t\",\"n2\":\"56\",\"n3\":\"4\"},{\"n7\":\"n7t\",\"n2\":\"2\",\"n3\":\"3\"},{\"n8\":\"n8t\",\"n2\":\"1\",\"n3\":\"4\"}]"; //eval(JsonObj) => JsonObj
//eval(JsonString) => JsonObj function gow()
{ alert( JTS(eval(a2)) );
alert(JTS(a1)); }
当然,你也 可以直接定义一个对象:
//定义一个对象
var a3={}