如何在特定索引处查找JSON数据

时间:2017-06-22 11:26:24

标签: javascript jquery ajax

我想只显示印度,斯里兰卡等国名。

{"result":1,"countries":[
    {"country_id":"1","country_name":"Afghanistan"},
    {"country_id":"2","country_name":"Albania"},
    {"country_id":"3","country_name":"Algeria"},
    {"country_id":"4","country_name":"American Samoa"},
    {"country_id":"5","country_name":"Andorra"},
    {"country_id":"6","country_name":"Angola"},
    {"country_id":"7","country_name":"Anguilla"}
    ]
}

2 个答案:

答案 0 :(得分:0)

为什么不迭代对象并将数据拉入单独的数组?例如:

[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
    console.log(element.country_name);
});

答案 1 :(得分:0)

下面我创建了与你的JSON对象相同的内容:

var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';

var obj = JSON.parse(text);

您可以遍历JSON对象并获取每个属性值,如下所示:

for(i = 0; i < obj.countries.length ; i++) 
{
    console.log(obj.countries[i].country_name);
}

希望这会有所帮助!