Parsing JSON in javascript for multiple JSON objects [closed]

泄露秘密 提交于 2021-02-18 21:13:06

问题


Should be quite a common answer but I haven't found it.

Using client-side javascript:

My client receives some JSON string:

response = 
[
 {"id1":"value1" , "time1":"valuetime1"},
 {"id2":"value2" , "time2":"valuetime2"}
]

I understand that I can simply parse the JSON string with this command:

response = JSON.parse(response);

But what is the next command to access each of the objects individually? I would prefer to not use jQuery.


回答1:


In plain JavaScript, just use a simple for loop:

for(var i = 0; i < response.length; i++){
    console.log(response[i]); // Object with id and time
}

-or-

response.forEach(function(object){
    console.log(object); 
});

Demo




回答2:


This JSON will become the appropriate JavaScript object. In this case, that is an array which you can access the same way as you would any other JavaScript array:

for (var i = 0; i < response.length; i++){
  console.log(response[i]);
}


来源:https://stackoverflow.com/questions/18877505/parsing-json-in-javascript-for-multiple-json-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!