简体   繁体   English

Rails从JSON数据访问哈希中的键

[英]Rails accessing keys in hashes from JSON data

I have a hash from a JSON object. 我有一个来自JSON对象的哈希。 It looks like this: 它看起来像这样:

JSON = {"kind"=>"calendar#freeBusy", "timeMin"=>"2012-02-19T19:35:00.000Z", "timeMax"=>"2012-02-19T19:40:00.000Z", "calendars"=>{"av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com"=>{"busy"=>[{"start"=>"2012-02-19T19:35:00Z", "end"=>"2012-02-19T19:40:00Z"}]}}} JSON = {“kind”=>“calendar#freeBusy”,“timeMin”=>“2012-02-19T19:35:00.000Z”,“timeMax”=>“2012-02-19T19:40:00.000Z”, “calendars”=> {“av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com”=> {“busy”=> [{“start”=>“2012-02-19T19:35:00Z”,“end”=>“ 2012-02-19T19:40:00Z“}]}}}

I want to check if there's any children of busy (a child of calendars). 我想检查是否有任何忙碌的孩子(日历的孩子)。

I can access the children of calendars by JSON["calendars"] 我可以通过JSON [“日历”]访问日历的孩子们

That returns: 返回:

{"av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com"=>{"busy"=>[{"start"=>"2012-02-19T19:35:00Z", "end"=>"2012-02-19T19:40:00Z"}]}} {“av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com”=> {“busy”=> [{“start”=>“2012-02-19T19:35:00Z”,“end”=>“2012-02-19T19 :40:00Z“}]}}

but JSON["calendars"]["busy"] (which is how I think you're meant to access child elements?) returns nil. JSON [“日历”] [“忙”] (这是我认为你打算访问子元素的方式?)返回nil。

How do I get inside the "busy" child? 如何进入“忙碌”的孩子?

I created the hash using JSON.parse to a Faraday request. 我使用JSON.parse创建了一个法拉第请求的哈希。

"busy" is nested under "av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com" in your case, so you need to include this as well: JSON["calendars"]["av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com"]["busy"].If you want access this attribute for all calendars, you'll have to loop: 在您的情况下,“busy”嵌套在“av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com”下,因此您还需要包含此内容:JSON [“calendars”] [“av3ddlgc54qe4brii4r7pius6k@group.calendar.google.com”] [ “忙”]。如果要为所有日历访问此属性,则必须循环:

JSON["calendars"].each do |key, value|
  # working with value["busy"]...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM