Link to home
Start Free TrialLog in
Avatar of bishop3000
bishop3000Flag for United States of America

asked on

How to extract values from string in Ruby on Rails

I'm a novice trying to extract the latitude and longitude values (under geometry > location) from the attached JSON.

I tried to use this legacy code without success:
   
    results_array = ActiveSupport::JSON.decode response.body

    if results_array && "OK" == results_array["status"]      
      results_array["results"].each do |result|
        puts logger.info lat = result["geometry"]["location"]["lat"]
   
    end

Open in new window


I figured out how to convert to key-value pairs with:
response_2 = JSON.parse(response.body)

Open in new window

...But still couldn't figure out how to extract the latitude and longitude.

I thought this would be obvious, but didn't find the solution through googling. Thanks a lot for your help.
JSON-text.txt
JSON-text-as-key-value-pairs.txt
ASKER CERTIFIED SOLUTION
Avatar of Andrew Doades
Andrew Doades
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bishop3000

ASKER

Thanks doades, the link got me on the right track.

Here's what I ended up with, which works.

  def get_site_geocoordinates  # Bishop 2014.01.18
    
    geocoder_url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="

    url = geocoder_url + ERB::Util.url_encode( params[:site_address] )
    uri = URI.parse(url)

    response = Net::HTTP.get_response(uri)
    
    geo_text = JSON.parse(response.body)
    


    response_text = ""

    if geo_text && "OK" == geo_text["status"]
      geo_text["results"].each do |result|
        response_text = "Latitude,\"#{result["geometry"]["location"]["lat"]}\"\n"   # entry["geometry"]["location"]["lat"].to_s
        response_text += "Longitude,\"#{result["geometry"]["location"]["lng"]}\"\n"
      end
    else
      response_text = "SiteAddress,\"0\"\n"
    end


    render :text => response_text, :content_type => "text/plain" 
  
  end

Open in new window

You're welcome, glad it helped you out :)