【发布时间】: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"]?