Ruby迭代JSON响应并返回值

时间:2016-07-20 20:09:53

标签: arrays ruby json hash

我正在尝试迭代JSON,并且我不断犯下以下错误:

no implicit conversion of String into Integer (TypeError)

我想要做的是迭代我的回复并根据我的规则返回一段数据。我的回答如下:

data = JSON.parse(response)

data = (whats below)

{
        “summary”: {
          “Id”: 5452,
          “IdOutcome”: "Scored",
          “Results”: [
            {
              “test”: "car",
              “value”: 10.0,
              “num”: 0
            },
            {
              “test”: "carz",
              “value”: 0.0,
              “num”: 0
            },
            {
              “test”: "bars",
              “value”: 10.0,
              “num”: 1
            }
          ]
        }
      }

因此,在上面的示例响应中,我想要遍历"结果"并返回" test"或者甚至是最高num值的所有块。所以在下面的例子中我将被退回

"bars",
10.0,
1

或只是

"bars"

基本上我只需要遍历返回的数组数据。

2 个答案:

答案 0 :(得分:0)

54a52无效。您可能需要在引号"54a52"中对其进行封装。如果你改变它,它将正确解析字符串。

JSON.parse('{"summary":{"Id":"54a52","IdOutcome":"Scored","Results":[{"test":"car","value":10.0,"num":0},{"test":"carz","value":0.0,"num":0},{"test":"bars","value":10.0,"num":1}]}}')
=> {"summary"=>{"Id"=>"54a52", "IdOutcome"=>"Scored", "Results"=>[{"test"=>"car", "value"=>10.0, "num"=>0}, {"test"=>"carz", "value"=>0.0, "num"=>0}, {"test"=>"bars", "value"=>10.0, "num"=>1}]}}

答案 1 :(得分:0)

您想使用Enumerable#max_by

max_result = data["summary"]["Results"].max_by {|r| r["num"] }
# => { "test" => "bars",
#      "value" => 10.0,
#      "num" => 1
#    }

max_result["test"]
# => "bars"