Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 使用Ruby搜索JSON响应_Ruby On Rails_Ruby_Json - Fatal编程技术网

Ruby on rails 使用Ruby搜索JSON响应

Ruby on rails 使用Ruby搜索JSON响应,ruby-on-rails,ruby,json,Ruby On Rails,Ruby,Json,我使用Ruby脚本与应用程序API接口,返回的结果是JSON格式的。例如: { "incidents": [ { "number": 1, "status": "open", "key": "abc123" } { "number": 2, "status": "open", "key": "xyz098" } { "number": 3, "status"

我使用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资源书进行几天的搜索并没有产生任何效果

有什么建议吗?

按以下步骤操作

# to get numbers from `'key'`.
json_hash["incidents"].map { |h| h['key'][/\d+/].to_i }
  • json\u hash[“事件”]
    -将为您提供键
    “事件”
    的值,它只是一个哈希数组

  • 遍历每个散列并收集
    'key'
    的值。然后应用于数组的每个内部散列,以获取
    “key”
    的值。然后调用,仅从
    “xyz098”
    中获取数字字符串,如
    “098”
    ,最后应用以从中获取实际整数

如果给定的散列实际上是一个
json
字符串,那么首先使用解析将其转换为散列,然后按照上面所述进行迭代

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

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

在变量中Strore上述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

h["incidents"].map {|h1| h1['number'] if h1['key']=='xyz098'}.compact.first
或者您也可以使用
find
,如下所示

 h["incidents"].find {|h1| h1['key']=='xyz098'}['number']
h["incidents"].select {|h1| h1['key']=='xyz098'}.first['number']
或者您也可以使用
选择
,如下所示

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

您正在寻找标准库的名称吗?散列之间需要逗号才能成为有效的可解析json。我试图编辑Q,但您需要更改6个字符-不能添加2个逗号:)我相信他要求的是带有键的散列的
“number”
字段
“xyz098”
这可以使用类似
json_散列[“事件”]的方式来完成。选择{h | h['key']='abc123'}。首先['number']
它提供了
2
不需要
的if
<每当块返回
true
时,code>select
find
抛出选择。只有
h1['key']=='xyz098'
就足够了。谢谢您的帮助!给我指出了正确的方向,我就能够解决这个问题。干杯