裁剪JSON的一部分

时间:2018-07-09 12:21:31

标签: javascript json node.js

我正在尝试解析JSON游戏结果统计信息并添加/更改/删除一些值:

bot.Dota2.requestMatchDetails(lobby.match_id);
bot.Dota2.on("matchDetailsData", function (matchId, matchData) {
    var data = JSON.parse(JSON.stringify(matchData));
    data.match.type = "partyStatistic";
    data.match.partyId = bot.currentLobby.id;
    for (i = 0; i < data.match.players.length; i++) {
        delete data.match.players[i].party_id;
        data.match.players[i].account_id = bot.Dota2.ToSteamID(data.match.players[i].account_id + "") + "";
    }
    delete data.vote;
    delete data.result;
    util.log(JSON.stringify('API STATISTIC: ' + JSON.stringify(data)));
}

JSON即时获取:

{
    "match": {
        "duration": 647,
        "startTime": 1530782586,
        "cluster": 136,
        "first_blood_time": 308,
        "lobby_type": 1,
        "human_players": 2,
        "positive_votes": 0,
        "negative_votes": 0,
        "game_mode": "DOTA_GAMEMODE_1V1MID",
        "radiant_team_score": 2,
        "dire_team_score": 0,
        "match_outcome": "k_EMatchOutcome_RadVictory",
        "pre_game_duration": 90,
        "type": "partyStatistic",
        "partyId": "54333333-0bea-e611-80bc-c8600054b63d"
    }
}

我需要的JSON

{
    "duration": 647,
    "startTime": 1530782586,
    "cluster": 136,
    "first_blood_time": 308,
    "lobby_type": 1,
    "human_players": 2,
    "positive_votes": 0,
    "negative_votes": 0,
    "game_mode": "DOTA_GAMEMODE_1V1MID",
    "radiant_team_score": 2,
    "dire_team_score": 0,
    "match_outcome": "k_EMatchOutcome_RadVictory",
    "pre_game_duration": 90,
    "type": "partyStatistic",
    "partyId": "54333333-0bea-e611-80bc-c8600054b63d"
}

我尝试使用以下方法在JSON的开头和结尾拆分一些符号:

data = JSON.parse(JSON.stringify(data).substring(9));
data = JSON.parse(JSON.stringify(data).substring(0, data.length - 1));

但是我遇到了错误。还有其他解决方案吗?谢谢。

1 个答案:

答案 0 :(得分:3)

尝试一下:

JSON.stringify(JSON.parse(data)["match"]);

或者如果数据已经只是一个json对象

JSON.stringify(data["match"])