简体   繁体   English

在Rails中的ruby中提取哈希数据

[英]extracting hash data in ruby on rails

I'm working with sabre api ( test licence ) in my rails application, i get a JSON response and when I parse it a get this hash 我在Rails应用程序中使用saber api(测试许可证),我得到JSON响应,当我解析它时得到此哈希

{
    "OriginLocation"=>"DEN",
    "Destinations"=>[
    {
    "Rank"=>1,
    "Destination"=>{
    "DestinationLocation"=>"LAX",
    "AirportName"=>"Los Angeles International Airport",
    "CityName"=>"Los Angeles",
    "CountryCode"=>"US",
    "CountryName"=>"United States",
    "RegionName"=>"North America",
    "Type"=>"Airport"
    }
    },
    {
    "Rank"=>2,
    "Destination"=>{
    "DestinationLocation"=>"LAS",
    "AirportName"=>"McCarran International Airport",
    "CityName"=>"Las Vegas",
    "CountryCode"=>"US",
    "CountryName"=>"United States",
    "RegionName"=>"North America",
    "Type"=>"Airport"
    }
    },
    {
    "Rank"=>3,
    "Destination"=>{
    "DestinationLocation"=>"CHI",
    "CountryCode"=>"US",
    "CountryName"=>"United States",
    "RegionName"=>"North America",
    "MetropolitanAreaName"=>"Chicago",
    "Links"=>[
    {
    "rel"=>"airportsInCity",
    "href"=>"https://api.test.sabre.com/v1/lists/supported/cities/CHI/airports"
    }
    ],
    "Type"=>"City"
    }
    } 
    ...
    }

How can i extract the data (ex: destination) information from it? 如何从中提取数据(例如:目的地)信息? I tried this code but i get an error " undefined method ``each' for nil:NilClass " 我尝试了这段代码,但出现错误" undefined method ``each' for nil:NilClass "

@hash['Destinations'].each do |key, value|
  puts key
  value.each do |k,v|
    puts k
    puts v
  end
end

Even though you've specified key and value , only key is populated (with the entire hash data), and value is nil . 即使您指定了keyvalue ,也仅填充key (带有整个哈希数据),并且valuenil That's why you're getting an error. 这就是为什么您会遇到错误。

Assuming you're on Ruby 2.3 or above, I suggest you use something like this instead: 假设您使用的是Ruby 2.3或更高版本,建议您改用以下代码:

@hash['Destinations'].map { |d| d.dig('Destination', 'CityName') }
#=> ["Los Angeles", "Las Vegas", nil]

You can read up more on dig here. 您可以在此处阅读更多关于dig信息。 It's useful for this kind of deeply nested data, and will protect you from keys that don't exist (and return nil instead); 这对于这种深度嵌套的数据很有用,并且可以保护您免受不存在的键的影响(并返回nil ); as long as you don't mix its usage on arrays and hashes. 只要您不将其用法混合在数组和哈希上即可。

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

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