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.
hash["metric_data"]["metrics"][0]["timeslices"]