Ruby深度嵌套JSON API数据 [英] Ruby getting deeply nested JSON API data
问题描述
我有一个Rails应用,该应用从World Weather Online API得到响应.我正在使用rest-client gem,响应为JSON格式.
我使用以下方法解析响应:
parsed_response = JSON.parse(response)
parsed_response
显然是哈希值.
我需要的数据是字符串内的散列,该字符串在一个散列内的一个数组内,在另一个散列内的另一个数组内,在另一个散列内.
最里面的嵌套哈希位于["hourly"]
内,该数组包含8个哈希,每个哈希有20个键,具有各种天气参数的字符串值.数组中的每个散列都是一天中的不同时间(预测是每小时3小时,3 * 8 = 24小时).
例如,如果我想在晚上9点以米为单位的膨胀高度,我可以通过以下电话找到它:
@swell_height = parsed_data["data"]["weather"][0]["hourly"][7]["swellHeight_m"]
数组中的第7个元素对应于"time" => "2100"
虽然我绝对可以使用它,但是我很好奇是否有一种更直接的方法来访问我的数据,例如,如果它是数据库表,那么我可以使用活动记录,例如:
@swell_height = parsed_data.swellHeight_m.where(:time => "2100")
您可能需要查看 JSONPath .它完全满足您的需求.它的语法与XPath非常相似,但是JSONPath可以处理JSON数据(很明显).
有一个Ruby实现: https://github.com/joshbuddy/jsonpath
我亲自在需要测试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)
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.
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).
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"]
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")
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).
There is a Ruby implementation: https://github.com/joshbuddy/jsonpath
I personally use it in every project where I need to test JSON responses.
这篇关于Ruby深度嵌套JSON API数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!