javascript 操作jsonArray

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函數。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章