标签:
一、jsonObject类型,直接看jsonArray类型
二、jsonArray类型,相对于jsonObject类型,外面需要多加一层遍历数组
注意下面2种获取内容的for..In循环里面的参数i和m,当时晕乎了,请教了人才明白
1>获取到json中的属性名称
1 var aData=[ 2 {width:‘20px‘,height:‘20px‘,left:‘40px‘,top:‘50px‘,background:‘#f00‘}, 3 {width:‘30px‘,height:‘30px‘,left:‘20px‘,top:‘20px‘,background:‘#ccc‘} 4 ]; 5 6 for(var i in aData) { 7 for (var m in aData[i]) { 8 console.log(m) 9 } 10 }
输出结果为
2>获取到json中的属性值
1 var aData=[ 2 {width:‘20px‘,height:‘20px‘,left:‘40px‘,top:‘50px‘,background:‘#f00‘}, 3 {width:‘30px‘,height:‘30px‘,left:‘20px‘,top:‘20px‘,background:‘#ccc‘} 4 ]; 5 for(var i in aData){ 6 for(var m in aData[i]){ 7 console.log(aData[i][m]) 8 } 9 }
输出结果为
3>获取到json中所有特定属性的属性值,比如我获取到每一个的属性名为 高度 的属性值
1 var aData=[ 2 {width:‘20px‘,height:‘20px‘,left:‘40px‘,top:‘50px‘,background:‘#f00‘}, 3 {width:‘30px‘,height:‘30px‘,left:‘20px‘,top:‘20px‘,background:‘#ccc‘} 4 ]; 5 for(var i in aData) { 6 console.log(aData[i].height) 7 }
输出结果为
3>复杂json
1 var aData = { 2 "china":{ 3 "hangzhou":{"item1":"1"}, 4 "shanghai":{"item2":"2"}, 5 "chengdu":{"item3":"3"} 6 }, 7 "America":{ 8 "aa":{"item1":"1"}, 9 "bb":{"item2":"2"} 10 }, 11 "Spain":{ 12 "dd":{"item1":"1"}, 13 "ee":{"item2":"2"}, 14 "ff":{"item3":"3"} 15 } 16 }; 17 for(var country in aData){ 18 document.write(country+‘‘+‘‘+‘<br>‘); 19 for(var city in aData[country]){ 20 document.write(city+‘>‘+‘‘) 21 for(var attr in aData[country][city]){ 22 document.write(attr+‘:‘+‘‘) 23 } 24 for(var value in aData[country][city][attr]){ 25 //document.write(value+‘‘+‘<br>‘)-->这样写不正确,因为value并不是对象,只是值而已 26 document.write(aData[country][city][attr][value]+‘‘+‘<br>‘) 27 } 28 } 29 }
输出结果为
1 var aData = { 2 "china":[ 3 {"name":"hangzhou", "item":"1"}, 4 {"name":"shanghai", "item":"2"}, 5 {"name":"sichuan", "item":"3"} 6 ], 7 "America":[ 8 {"name":"aa", "item":"12"}, 9 {"name":"bb", "item":"2"} 10 ], 11 "Spain":[ 12 {"name":"cc", "item":"1"}, 13 {"name":"dd", "item":"23"}, 14 {"name":"ee", "item":"3"} 15 ] 16 } 17 for(var country in aData){ 18 document.write(country+‘‘+‘‘+‘<br>‘) 19 for(var cityObj in aData[country] ){//遍历jsonArray 20 for(var cityName in aData[country][cityObj]) { 21 document.write(cityName + ‘>‘)//输出属性名 22 for (var cityItem in aData[country][cityObj][cityName]) { 23 document.write(aData[country][cityObj][cityName][cityItem])//输出属性值 24 } 25 } 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/Nomand/p/4263372.html