JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString
如下示例:
直接写的a1就是一个Json对象,a2 就是一个Json对象字符串; 通过eval函数 得到的 都是Json对象, 不管参数是对象还是 字符串.
1 function JTS(o){ 2 var arr = []; 3 var fmt = function(s) { 4 if (typeof s == "object" && s != null) 5 return JTS(s); 6 return /^(string|number)$/.test(typeof s) ? """ + s + """ : s; 7 } 8 for (var i in o) 9 arr.push(""" + i + "":" + fmt(o[i])); 10 return "{" + arr.join(",") + "}"; 11 } 12
13 //Json 对象 14 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"}]; 15 //Json对象字符串 16 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"}]"; 17 18 //eval(JsonObj) => JsonObj 19 //eval(JsonString) => JsonObj 20 21 function gow() 22 { 23 24 alert( JTS(eval(a2)) ); 25 alert(JTS(a1)); 26 32 }
当然,你也 可以直接定义一个对象:
//定义一个对象 var a3={}