Ruby getting deeply nested JSON API data

断了今生、忘了曾经 提交于 2021-02-16 16:11:17

问题


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")

回答1:


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.



来源:https://stackoverflow.com/questions/12574838/ruby-getting-deeply-nested-json-api-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!