如何在Jquery中迭代JSON数组

时间:2016-05-13 19:08:38

标签: javascript jquery arrays json

我有以下类型的数组。我想在JavaScript中迭代这个数组。这怎么可能?

{
"result": true,
"data": [
{
    "ID": 1,
    "stage_ID": 1,
    "badge_type_ID": 1,
    "name": "Despertar da Força",
    "description": "Fazer a primeira SuperAtividade",
    "type": "",
    "image_static": "url123.jpg",
    "image_animated": "",
    "SQL": "",
    "published": 1
},
{
    "ID": 2,
    "stage_ID": 1,
    "badge_type_ID": 1,
    "name": "Super 3",
    "description": "Fazer 3 SuperAtividades",
    "type": "",
    "image_static": "urlimage123.png",
    "image_animated": "",
    "SQL": "",
    "published": 1
}

我尝试了以下脚本,它正在返回" undefined"," undefined"。

$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
        var output= "<ol>";
        for (var i in data) {
            output += "<li>" + data[i].ID + "</li>"
        }
        output+="</ol>";
        document.getElementById("placeholder").innerHTML=output;
    }); 

任何解决方案?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以尝试转换为Json对象

$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
        var output= "<ol>";
        var jsondata = $.JSON.parse(data); // Json object Convertion
        for (var i in data) {
            output += "<li>" + data[i].ID + "</li>"
        }
        output+="</ol>";
        document.getElementById("placeholder").innerHTML=output;
    });

答案 1 :(得分:0)

您正尝试使用 data [i] .ID 访问未定义的属性。

当您从 getJSON()函数获得响应时,您需要使用名称调用响应,然后您可以使用此名称访问任何内部属性。

现在,如果你想在myResponse变量上使用数据键/值进行迭代,那么你需要这样做。

$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(myResponse) {
    var output= "<ol>";
    var dataCount = myResponse.data.length;
    for (var i = 0; i < dataCount; i++) {
        output += "<li>" + myResponse.data[i].ID + "</li>";
    }
    output+="</ol>";
    document.getElementById("placeholder").innerHTML=output;
});