如何使用Ruby解析JSON数组?

时间:2022-10-22 20:42:02

I'm working with a third-party API. I'm trying to parse JSON using Ruby. JSON response:

我正在使用第三方API。我正在尝试使用Ruby解析JSON。 JSON响应:

{
  "metric_data": {
    "from": "2014-09-22T23:33:20+00:00",
    "to": "2014-09-23T00:03:20+00:00",
    "metrics": [
      {
        "name": "HttpDispatcher",
        "timeslices": [
          {
            "from": "2014-09-22T23:32:00+00:00",
            "to": "2014-09-23T00:01:59+00:00",
            "values": {
              "requests_per_minute": 85700
            }
          }
        ]
      }
    ]
  }
}

The data that I need to access is requests_per_minute. Since JSON.parse returns a Hash, it seems like I would just able to access this using keys:

我需要访问的数据是requests_per_minute。由于JSON.parse返回一个哈希,似乎我只能使用键来访问它:

hash = JSON.parse(response.body)

data = hash["metric_data"]

The previous code would produce a nested level down, like this:

前面的代码会产生嵌套级别,如下所示:

{
  "from": "2014-09-22T23:33:20+00:00",
  "to": "2014-09-23T00:03:20+00:00",
  "metrics": [
    {
      "name": "HttpDispatcher",
      "timeslices": [
        {
          "from": "2014-09-22T23:32:00+00:00",
          "to": "2014-09-23T00:01:59+00:00",
          "values": {
            "requests_per_minute": 85700
          }
        }
      ]
    }
  ]
}

However, if I try to nest any further, the response becomes an Array and I receive an error:

但是,如果我尝试进一步嵌套,响应将成为一个数组,我收到一个错误:

data = hash["metric_data"]["metrics"]["timeslices"]

no implicit conversion of String into Integer (TypeError)

I believe the error is that "metrics" and "timeslices" appear to be JSON Arrays, using [] instead of {}. I really need a sanity check. What am I missing here? I'm just trying to access requests_per_minute.

我认为错误是“metrics”和“timeslices”似乎是JSON Arrays,使用[]而不是{}。我真的需要一个健全检查。我在这里想念的是什么?我只是想尝试访问requests_per_minute。

1 个解决方案

#1


3  

You're correct, it's parsing "metrics" and "timeslices" each as an Array of Hashes, so try this:

你是对的,它正在将“metrics”和“timeslices”解析为一个Hashes数组,所以试试这个:

requests_per_minute = hash["metric_data"]["metrics"][0]["timeslices"][0]["values"]["requests_per_minute"]

#1


3  

You're correct, it's parsing "metrics" and "timeslices" each as an Array of Hashes, so try this:

你是对的,它正在将“metrics”和“timeslices”解析为一个Hashes数组,所以试试这个:

requests_per_minute = hash["metric_data"]["metrics"][0]["timeslices"][0]["values"]["requests_per_minute"]