作为我的另一个 thread 中的另一个用户建议在这里发布另一个关于解释如何访问 JSON 对象的问题。我使用的代码是:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>
我想用the JSON code做什么,就是搜索指定的world_id
并返回match_id
。我对 JavaScript 很陌生,所以我不太确定如何做到这一点,以及如何访问上面代码给我的字符串化数据。
我想出如何做到这一点的方法是创建一个数组并将每个对象存储在其中,然后循环并检查匹配的 id,例如,
if(obj[i].red_world_id == 'xxxx' || obj[i].blue_world_id == 'xxxx' || obj[i].green_world_id == 'xxxx') {
return obj[i].wvw_match_id;
}
我唯一的问题是我不知道如何将数组设置为 JSON 数据。
最佳答案
.使用此代码 -
$(function() {
$.getJSON("https://api.guildwars2.com/v1/wvw/matches.json", function(
data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
var result = [];//for if it has many matches
for ( var i=0;i<data.wvw_matches.length;i++ ) {
var obj = data.wvw_matches[i];
if (obj.red_world_id == 'xxxx' || obj.blue_world_id == 'xxxx'
|| obj.green_world_id == 'xxxx') {
result.push(obj.wvw_match_id);
}
}
});
});
关于javascript - 访问字符串化的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18364560/