32423hjh32423
32423hjh32423

Reputation: 3088

Easy way to access hashes from within arrays with ruby

I'm using ruby to get get some address information from the Google geocode API. I get JSON returned and parse this into a variable which is an array containing hashes.

After I've parsed the json it looks like this

{"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"}]}

My ruby looks like this

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

The mixture of hashjes and arrays is confusing me in Ruby. I wish to extract the information into one hash to look something like this

result = { "address_line_one" => "XXX St Georges Terrace", "address_line_two" => "Perth", "state" => "Western Austalia", "postal_code" => "6000" }

Thanks

Upvotes: 1

Views: 1143

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146043

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] }
)

Upvotes: 2

Related Questions