Js 怎么遍历json对象所有key及根据动态key获取值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Js 怎么遍历json对象所有key及根据动态key获取值相关的知识,希望对你有一定的参考价值。

var obj = ;
for(var k in obj) 

    //遍历对象,k即为key,obj[k]为当前k对应的值
    console.log(obj[k]);

参考技术A

json是种常用数据传输格式,js怎么解析json格式的数据呢,请参阅下面的代码:

[html] view plain copy print?

    <html>  

    <head>  

    <script type="text/javascript">  

    var data = '"return_code":0,"return_message":"success","data":"data":["id":"1","question":"公主令牌在哪交?","id":"2","question":"公主护使有什么用?","id":"3","question":"角斗场在哪?","id":"4","question":"北部断层在哪?","id":"5","question":"欢乐令有什么用?","id":"6","question":"令牌积分有什么用?","id":"7","question":"南部断层在哪?","id":"8","question":"大妖魔令牌交给谁?","id":"9","question":"神工坊在哪?","id":"10","question":"警戒妖珠有什么用?"]';  

    function ShowData()          

    var obj = eval("("+data+")");         

    alert("return_code:"+obj["return_code"]);  

    alert("return_message:"+obj["return_message"]);  

    alert("第一个问题id:" + obj["data"]["data"][0]["id"]);  

    alert("第一个内容id:" + obj["data"]["data"][0]["question"]);  

      

    </script>  

    </head>  

    <body onload="ShowData();">  

    "return_code":0,"return_message":"success","data":"data":["id":"1","question":"公主令牌在哪交?","id":"2","question":"公主护使有什么用?","id":"3","question":"角斗场在哪?","id":"4","question":"北部断层在哪?","id":"5","question":"欢乐令有什么用?","id":"6","question":"令牌积分有什么用?","id":"7","question":"南部断层在哪?","id":"8","question":"大妖魔令牌交给谁?","id":"9","question":"神工坊在哪?","id":"10","question":"警戒妖珠有什么用?"]  

    </body>  

    </html>  

参考资料

json官网.json官网[引用时间2018-1-2]

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

以上是关于Js 怎么遍历json对象所有key及根据动态key获取值的主要内容,如果未能解决你的问题,请参考以下文章

json对象遍历输出key和value

怎样用for循环动态遍历json数组

js匹配一个对象中key的值进行合并到新的对象

用js遍历当前窗体的所有子窗体

json 的key可以是对象吗

js中怎么获取json中的key,value值?