【问题标题】:Ruby : select specific element of a parsed jsonRuby:选择已解析 json 的特定元素
【发布时间】:2021-11-13 05:56:16
【问题描述】:

我正在尝试使用 Ruby 解析我的 JSON 的特定部分。 我从服务器获取这个字符串:

[   {
    "id": 1,
    "player_id": "not_this_one\n",
    "highscore": 23   },   {
    "id": 2,
    "player_id": "id_to_get\n",
    "highscore": 44   },   {
    "id": 3,
    "player_id": "not_this_one_either\n",
    "highscore": 278   } ]

我想提取第二个“played_id”与字符串“id_to_get”匹配的玩家的高分。

我设法编写了代码:

response = HTTPLite.get("http://some-api")
if response[:status] == 200
  parsed = HTTPLite::JSON.parse(response[:body])
  p parsed[0]
end

输出我的 json 的第一部分,即:"{ "id": 1, "player_id": "not_this_one\n", "highscore": 23 }"

如何更改 [0] 以专门提取我想要的 json 部分?

提前感谢您的帮助。

【问题讨论】:

  • parsed.dig(1, "highscore")parsed.find { |parsed_i| parsed_i["player_id"] == "id_to_get\n" }["highscore"]?

标签: arrays json ruby parsing


【解决方案1】:

parsed[0] 正在返回 parsed 数组中的第一项。如果您想退回第二项,您可以使用parsed[1]

但是你可能不知道数组的顺序,所以你可以检查你想要的player_id

parsed.find {|x| x[:player_id] == "id_to_get\n" }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多