使用ruby从数组内部访问哈希的简便方法

时间:2011-06-12 23:14:23

标签: ruby json

我正在使用ruby从Google地理编码API获取一些地址信息。我返回JSON并将其解析为变量,该变量是包含哈希的数组。

在我解析了json后,它看起来像这样

{"status"=>"OK",
 "results"=>
  [{"address_components"=>
     [{"long_name"=>"XXX", "types"=>["street_number"], "short_name"=>"XXX"},
      {"long_name"=>"St Georges Terrace",
       "types"=>["route"],
       "short_name"=>"St Georges Terrace"},
      {"long_name"=>"Perth",
       "types"=>["locality", "political"],
       "short_name"=>"Perth"},
      {"long_name"=>"Western Australia",
       "types"=>["administrative_area_level_1", "political"],
       "short_name"=>"WA"},
      {"long_name"=>"Australia",
       "types"=>["country", "political"],
       "short_name"=>"AU"},
      {"long_name"=>"6000", "types"=>["postal_code"], "short_name"=>"6000"}],
    "types"=>["street_address"],
"geometry"=>
 {"location_type"=>"ROOFTOP",
  "viewport"=>
   {"northeast"=>{"lng"=>115.86768092068, "lat"=>-31.9540383793198},
    "southwest"=>{"lng"=>115.86138567932, "lat"=>-31.9603336206802}},
  "location"=>{"lng"=>115.8645333, "lat"=>-31.957186}},
"formatted_address"=>"XXX St Georges Terrace, Perth WA 6000, Australia"}]}

我的红宝石看起来像这样

require 'rubygems'
require 'json'
require 'open-uri'
require 'pp'

@url = "http://maps.googleapis.com/maps/api/geocode/json?address=PERTH+XXX+St+Georges+Terrace,+Western+Australia&sensor=false"

uri = URI.parse(@url)
json = uri.open.read

parsed_json = JSON.parse(json)

pp parsed_json

hashjes和数组的混合使我在Ruby中感到困惑。我希望将信息提取到一个哈希中,看起来像这样

result = {“address_line_one”=> “XXX St Georges Terrace”,“address_line_two”=> “珀斯”,“州”=> “Western Austalia”,“postal_code”=> “6000”}

由于

1 个答案:

答案 0 :(得分:2)

j = parsed_json
a = j['results'][0]['address_components'].map { |e| e['long_name'] }

p(
  { 'address_line_one' => a[0..1].join(' '),
    'address_line_two' => a[2],
    'state'            => a[3],
    'postal_code'      => a[5] }
)