1

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

{
  "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:

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.

1
  • hash["metric_data"]["metrics"][0]["timeslices"] Sep 23, 2014 at 18:40

1 Answer 1

6

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

requests_per_minute = hash["metric_data"]["metrics"][0]["timeslices"][0]["values"]["requests_per_minute"]
2
  • Thanks for your answer, I was able to access RPM. I'm curious about how it works: using [0] just allows you access the first element of each nested Array?
    – user1678808
    Sep 23, 2014 at 18:45
  • Yes, correct. Arrays are index based with the first being 0. Presumably, you could have more than one "metrics" or "timeslices" in the result.
    – Donovan
    Sep 23, 2014 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.