使用Ruby搜索JSON响应

时间:2014-03-14 20:52:24

标签: ruby-on-rails ruby json

我使用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资源书并没有产生任何有用的东西。

有什么建议吗?

2 个答案:

答案 0 :(得分:37)

首先,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)

使用number

查找所需的map
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']

答案 1 :(得分:3)

执行以下操作

# 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