Ruby 获取深度嵌套的 JSON API 数据 [英] Ruby getting deeply nested JSON API data

查看:35
本文介绍了Ruby 获取深度嵌套的 JSON API 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Rails 应用程序,它从 World Weather Online API 获得响应.我正在使用 rest-client gem 并且响应采用 JSON 格式.

I have a rails app which gets a response from World Weather Online API. I'm using the rest-client gem and the response is in JSON format.

我使用以下方法解析响应:

I parse the response using:

parsed_response = JSON.parse(response)

其中 parsed_response 显然是一个哈希值.

Where parsed_response is obviously a hash.

我需要的数据是散列内的字符串,散列内的数组内的散列内的散列内的另一个散列内的另一个散列内的散列.

The data I need are strings inside a hash inside an array inside a hash inside another array inside another hash inside another hash.

最内层嵌套的散列在 ["hourly"] 内,这是一个由 8 个散列组成的数组,每个散列有 20 个键,拥有各种天气参数的字符串值.数组中的每个哈希值都是一天中的不同时间(预测为 3 小时一次,3*8 = 24 小时).

The inner-most nested hashes are inside ["hourly"], an array of 8 hashes, each with 20 keys, possessing string values of various weather parameters. Each of these hashes in the array is a different time of day (the forecast is three-hourly, 3*8 = 24hours).

因此,例如,如果我想要在晚上 9 点以米为单位的膨胀高度,我可以通过以下调用找到它:

So, for example, if I want the swell height in metres at 9pm, I find it with the following call:

@swell_height = parsed_data["data"]["weather"][0]["hourly"][7]["swellHeight_m"]

其中数组中的第 7 个元素对应于 "time" =>2100"

Where the 7th element in the array correspond to "time" => "2100"

虽然我绝对可以使用它,但我很好奇是否有更直接的方法来访问我的数据,比如如果它是一个数据库表,我可以使用活动记录,例如:

While I can definitely work with this, I'm curious as to whether there is a more straightforward method of accessing my data, like if it was a database table, I could use active record, something like:

@swell_height = parsed_data.swellHeight_m.where(:time => "2100")

推荐答案

您可能需要查看 JSONPath.它完全符合您的需求.它的语法与 XPath 非常相似,但 JSONPath 可以处理 JSON 数据(很明显).

You may want to look at JSONPath. It does exactly what you need. Its syntax is very similar to XPath, but JSONPath works with JSON data (as obvious).

有一个 Ruby 实现:https://github.com/joshbuddy/jsonpath

There is a Ruby implementation: https://github.com/joshbuddy/jsonpath

我个人在需要测试 JSON 响应的每个项目中都使用它.

I personally use it in every project where I need to test JSON responses.

这篇关于Ruby 获取深度嵌套的 JSON API 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆