我在我的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"
}
}
...
}
如何从中提取数据(例如:目的地)信息?
我试过这段代码,但收到错误" 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
答案 0 :(得分:0)
即使您已指定key
和value
,也只会填充key
(包含整个哈希数据),value
为nil
}。这就是您收到错误的原因。
假设您使用的是Ruby 2.3或更高版本,我建议您使用类似的内容:
@hash['Destinations'].map { |d| d.dig('Destination', 'CityName') }
#=> ["Los Angeles", "Las Vegas", nil]
您可以在dig
阅读更多内容。它对于这种深层嵌套的数据非常有用,它可以保护您免受不存在的密钥的影响(并返回nil
);只要你不在数组和哈希上混用它。