[英]How to parse JSON array using Ruby?
I'm working with a third-party API. 我正在使用第三方API。 I'm trying to parse JSON using Ruby.
我正在尝试使用Ruby解析JSON。 JSON response:
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
. 我需要访问的数据是
requests_per_minute
。 Since JSON.parse
returns a Hash, it seems like I would just able to access this using keys: 由于
JSON.parse
返回一个Hash,看来我只能使用键来访问它:
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 {}
. 我相信错误是使用
[]
而不是{}
, "metrics"
和"timeslices"
似乎是JSON数组。 I really need a sanity check. 我真的需要进行健全性检查。 What am I missing here?
我在这里想念什么? I'm just trying to access
requests_per_minute
. 我只是尝试访问
requests_per_minute
。
没错,它会将“指标”和“时间片”分别解析为哈希数组,因此请尝试以下操作:
requests_per_minute = hash["metric_data"]["metrics"][0]["timeslices"][0]["values"]["requests_per_minute"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.