function testJsonArray(){
var msg=[{"id":"/resources/common","pId":"/resources","name":"common","path":"/resources/common","isParent":true,"type":"nt:folder"},{"id":"/resources/element","pId":"/resources","name":"element","path":"/resources/element","isParent":true,"type":"nt:folder"},{"id":"/resources/css","pId":"/resources","name":"css","path":"/resources/css","isParent":true,"type":"nt:folder"},{"id":"/resources/scripts","pId":"/resources","name":"scripts","path":"/resources/scripts","isParent":true,"type":"nt:folder"},{"id":"/resources/contents","pId":"/resources","name":"contents","path":"/resources/contents","isParent":false,"type":"nt:folder"},{"id":"/resources/images","pId":"/resources","name":"images","path":"/resources/images","isParent":true,"type":"nt:folder"},{"id":"/resources/product","pId":"/resources","name":"product","path":"/resources/product","isParent":true,"type":"nt:folder"},{"id":"/resources/test","pId":"/resources","name":"test","path":"/resources/test","isParent":true,"type":"nt:folder"}];
var objs=eval(msg); //eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。
var item="";
//遍历Objs obj[x] 代表了一个jsonArray中的一个元素。 objs[x].值 代表了元素的值的key,如第一个node的Id objs[x].id
for(x in objs){
objs[x].index=x;
for(t in objs[x]){
item+=t;
item+=":"
item+=objs[x][t];
item+=" ";
}
item+="<br>";
}
var str=JSON.stringify(item);
$j("#info").html(str);
}
为了将JSON文本转换为对象,可以使用eval函数。eval函数调用JavaScript编辑器。由于JSON是JavaScript的子集,因此编译器将正确的解析文本并产生对象结构。文本必须括在括号中避免产生JavaScript的语法歧义。
var obj = eval('(' + JSONTest + ')');
eval函数非常快速。它可以编译执行任何JavaScript程序,因此产生了安全性问题。当使用可信任与完善的源代码时才可以使用eval函数。这样可以更安全的解析JSON文本。使用XmlHttp的web应用,页面之间的通讯只允许同源,因此是可以信任的。但这却不是完善的。如果服务器没有严谨的JSON编码,或者没有严格的输入验证,那么可能传送包括危险脚本的无效JSON文本。eval函数将执行恶意的脚本。
JSON解释器 JSON.parse、JSON.stringify
使用JSON解析器可以防止像eval函数转换JSON文本为对象那样的安全隐患。JSON解析器只能辨识JSON文本,拒绝所有脚本。提供了本地JSON支持的浏览器的JSON解析器将远快于eval函数。