1. 程式人生 > >js遍歷json

js遍歷json

rdl bsp 數組 ++ data- tracking bar popu -m

js遍歷json的key和value

轉載 2016年06月17日 17:26:55

原生js遍歷json對象

遍歷json對象:

無規律:

<script>
var json = [{dd:‘SB‘,AA:‘東東‘,re1:123},{cccc:‘dd‘,lk:‘1qw‘}];
for(var i=0,l=json.length;i<l;i++){
for(var key in json[i]){
alert(key+‘:‘+json[i][key]);
}
}
</script>

有規律:

packJson = [

{"name":"nikita", "password":"1111"},

{"name":"tony", "password":"2222"}

];

for(var p in packJson){//遍歷json數組時,這麽寫p為索引,0,1

   alert(packJson[p].name + " " + packJson[p].password);

}

也可以用這個:

for(var i = 0; i < packJson.length; i++){

   alert(packJson[i].name + " " + packJson[i].password);

}

遍歷json對象

myJson = {"name":"caibaojian", "password":"1111"};

for(var p in myJson){//遍歷json對象的每個key/value對,p為key

   alert(p + " " + myJson[p]);

}
有如下 json對象:
var obj ={"name":"馮娟","password":"123456","department":"技術部","sex":"女","old":30};
遍歷方法:
for(var p in obj){
str = str+obj[p]+’,‘;
return str;
}

js遍歷json