使用Ruby搜索JSON响应

20

我正在使用一个Ruby脚本与一个应用程序API进行交互,返回的结果是JSON格式。例如:

{
  "incidents": [
    {
      "number": 1,
      "status": "open",
      "key": "abc123"
    }
    {
      "number": 2,
      "status": "open",
      "key": "xyz098"
    }
    {
      "number": 3,
      "status": "closed",
      "key": "lmn456"
    }
  ]
}

我希望搜索每个区块找出特定的“关键”值(例如此例子中的yzx098),并返回相关的“数值”。

现在,我对Ruby非常陌生,不确定是否已经有函数可以帮助完成这个任务。然而,几天在谷歌和Ruby资源书籍上搜寻没有得到任何有效的结果。

有什么建议吗?


你是否在寻找标准库中的 JSON 模块 - matt
1
哈希值之间需要逗号才能成为有效的可解析JSON格式。我试图编辑Q,但你需要更改6个字符 - 不能添加2个逗号 :) - Mike Vormwald
2个回答

46

首先,JSON应该如下所示:(注意逗号)

 {
  "incidents": [
    {
      "number": 1,
      "status": "open",
      "key": "abc123"
    },
    {
      "number": 2,
      "status": "open",
      "key": "xyz098"
    },
    {
      "number": 3,
      "status": "closed",
      "key": "lmn456"
    }
  ]
}

将上述JSON存储在一个变量中

s =  '{"incidents": [{"number": 1,"status": "open","key": "abc123"},{"number": 2,"status": "open","key": "xyz098"},{"number": 3,"status": "closed","key": "lmn456"}]}'

解析JSON

h = JSON.parse(s)

使用 map 查找所需的number

h["incidents"].map {|h1| h1['number'] if h1['key']=='xyz098'}.compact.first

您也可以像下面这样使用find

 h["incidents"].find {|h1| h1['key']=='xyz098'}['number']

或者你也可以像下面这样使用select

h["incidents"].select {|h1| h1['key']=='xyz098'}.first['number']

不需要使用 ifselectfind 来进行选择,只要块返回 true。仅使用 h1['key']=='xyz098' 就足够了。 - Arup Rakshit
谢谢你的帮助!指引我正确的方向,我已经解决了这个问题。干杯! - Kristopher

4

按照以下步骤进行:

# to get numbers from `'key'`.
json_hash["incidents"].map { |h| h['key'][/\d+/].to_i }
  • json_hash["incidents"] - 这将给你"incidents"这个关键字的值, 它是一个数组。

  • map循环遍历每个哈希值并收集'key'的值。然后,对数组中的每个内部哈希应用 Hash#[] 来获取"key"的值。接着,调用 str[regexp] 来仅获取类似于'098'的数字字符串 从"xyz098"中,最后应用to_i来获得实际整数。

如果给定的哈希值实际上是一个json字符串,那么首先使用 JSON::parse 将其转换为哈希值,然后像我上面说的那样进行迭代。

require 'json'

json_hash = JSON.parse(json_string)
# to get values from the key `"number"`.
json_hash["incidents"].map { |h| h['number'] } # => [1, 2, 3]
# to search and get all the numbers for a particular key match and take the first
json_hash["incidents"].select { |h| h['key'] == 'abc123' }.first['number'] # => 1
# or to search and get only the first number for a particular key match
json_hash["incidents"].find { |h| h['key'] == 'abc123' }['number'] # => 1

我相信他是在要求获取键为“xyz098”的哈希表中的“number”字段。可以使用类似于json_hash["incidents"].select { |h| h['key'] == 'abc123' }.first['number']这样的代码来实现,它会返回值为2 - Mike Vormwald

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接