访问字符串化的JSON对象

Accessing stringified JSON objects

本文关键字:JSON 对象 字符串 访问      更新时间:2023-09-26

我的另一个线程中的另一位用户建议在这里发布另一个问题,解释如何访问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>

我试图对JSON代码进行的操作是搜索指定的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);
            }
        }
    });
});

不需要字符串化,您可以直接使用JSON对象:

function(data) {
    var filteredArray=$.grep(data.wvw_matches, function (item) {
        return (item.red_world_id == 'xxxx' || item.blue_world_id == 'xxxx' || item.green_world_id == 'xxxx');
    });
}

有关jQuery.grep.

的信息,请参阅此页