js遍历json的key和value

遍历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;
}

原文连接:http://blog.csdn.net/q1054261752/article/details/51701532

posted @ 2017-11-13 19:32  陈无问  阅读(46508)  评论(0编辑  收藏  举报