使用 Ruby 搜索 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22415525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:26:39  来源:igfitidea点击:

Search a JSON Response using Ruby

ruby-on-railsrubyjson

提问by Kristopher

I'm using a Ruby script to interface with an application API and the results being returned are in a JSON format. For example:

我正在使用 Ruby 脚本与应用程序 API 交互,并且返回的结果采用 JSON 格式。例如:

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

I'm looking to search each block for a particular "key" value (yzx098 in this example) and return the associated "number" value.

我希望在每个块中搜索特定的“键”值(在本例中为 yzx098)并返回关联的“数字”值。

Now, I'm very new to Ruby and I'm not sure if there's already a function to help accomplish this. However, a couple days of scouring the Googles and Ruby resource books hasn't yielded anything that works.

现在,我对 Ruby 很陌生,我不确定是否已经有一个函数可以帮助完成这个任务。然而,几天的搜索谷歌和 Ruby 资源书籍并没有产生任何有用的东西。

Any suggestions?

有什么建议?

回答by Kirti Thorat

First of all, the JSON should be as below: (note the commas)

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

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

Strore the above json in a variable

将上面的 json 存储在一个变量中

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

Parse the JSON

解析 JSON

h = JSON.parse(s)

Find the required numberusing map

找到所需的number使用map

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

Or you could also use findas below

或者你也可以使用find如下

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

Or you could also use selectas below

或者你也可以使用select如下

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

回答by Arup Rakshit

Do as below

做如下

# to get numbers from `'key'`.
json_hash["incidents"].map { |h| h['key'][/\d+/].to_i }
  • json_hash["incidents"]- will give you the value of the key "incidents", which is nothing but an array of hash.

  • mapto iterate thorough each hash and collect the value of 'key'. Then applying Hash#[]to each inner hash of the array, to get the value of "key". Then calling str[regexp], to get only the number strings like '098'from "xyz098", finally applying to_ito get the actual integer from it.

  • json_hash["incidents"]- 会给你 key 的值"incidents",它只是一个散列数组。

  • map遍历每个散列并收集 的值'key'。然后应用Hash#[]到数组的每个内部散列,以获取 的值"key"。然后调用str[regexp], 只获取像'098'from的数字字符串"xyz098",最后申请to_i从中获取实际整数。

If the given hash actually a jsonstring, then first parse it using JSON::parseto convert it to a hash.Then do iterate as I said above.

如果给定的散列实际上是一个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