JS循环遍历JSON数据

<html>
<head><title>JS遍历json数组</title></head>
<body>
	<script type="text/javascript">
		var data = [{name:"aaa",age:12},{name:"bbb",age:11},{name:"ccc",age:13},{name:"ddd",age:14}];  
		document.write("data : " + data);
		
		// js 遍历json数组
		for (var item in data) {
			name = data[item].name
			age = data[item].age
			
			document.write("</br>");
			document.write("</br>item : " + item);
			document.write("</br>data[item] : " + data[item]);
			document.write("</br>" + name + ", " + age);
		}
	</script>
	
	</br></br>
	
	<script type="text/javascript">
		
		// js 使用eval处理json
		try {
			document.write("</br>");
			var strJson = "{name:'json name', age:12}";
			var obj = new Function("return" + strJson)();	// 转换成 json 对象
			document.write("</br>" + obj.name + ", " + obj.age);
			
			
			var obj = eval("(" + strJson + ")");
			document.write("</br>" + obj.name + ", " + obj.age);
		} catch(ex) {
			document.write("</br>eror: " + ex);
		} finally {
			document.write("</br>");
			document.write("</br>");
		}
		
		// js使用eval处理json并遍历
		function printJson() {
			try {
				var json = "{options:[{text:'王家湾',value:'9'},{text:'李家湾',value:'10'},{text:'邵家湾',value:'13'}]}";
				var json = "{options:[{'text':'王家湾',value:'9'},{'text':'李家湾',value:'10'},{'text':'邵家湾',value:'13'}]}";
				json = eval("(" + json + ")");
				document.write("</br>json : " + json);					// json全部是 object
				
				jsonOptions = json.options;
				document.write("</br>jsonOptions : " + jsonOptions);	// 数组元素全部是 object
				
				document.write("</br>jsonOptions.length : " + jsonOptions.length);
				for (var i=0; i<jsonOptions.length; i++) {
					txt = jsonOptions[i].text;
					value = jsonOptions[i].value;
					
					document.write("</br>");
					document.write(txt + "; " + value);
				}
			} catch(ex) {
				document.write("</br>error: " + ex);
			} finally {
				document.write("</br>done!!");
			}
		}
		
		printJson();
	</script>
</body>
</html>

运行结果:

data : [object Object],[object Object],[object Object],[object Object]

item : 0
data[item] : [object Object]
aaa, 12

item : 1
data[item] : [object Object]
bbb, 11

item : 2
data[item] : [object Object]
ccc, 13

item : 3
data[item] : [object Object]
ddd, 14 



json name, 12
json name, 12


json : [object Object]
jsonOptions : [object Object],[object Object],[object Object]
jsonOptions.length : 3
王家湾; 9
李家湾; 10
邵家湾; 13
done!!