javascript - 访问字符串化的 JSON 对象

标签 javascript jquery json

作为我的另一个 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/

相关文章:

javascript - 强制水平负载

javascript - jQuery 不选择选项元素

javascript - 处理 RequireJS 必需类

javascript - bxslider 滑动对齐中心

精确到秒的 Javascript 模糊时间(例如 '10 minutes ago')

java - 按映射中的特定键对 List<Map<String, Object>> 进行排序

c# - Asp.net core WebApi 中空值的自定义序列化

JavaScript/jQuery : rotate element on key press (tetris effect)

javascript - 加载大量图像而不卡顿的最佳方式。

javascript - 模块/命名空间的一般 TypeScript 用法