Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing data from httparty response

Using httparty I can get the following response:

puts Representative.find_by_zip(46544).inspect

-->

{"results"=>[{"name"=>"Joe Donnelly", "district"=>"2", "office"=>"1218 Longworth", "phone"=>"(202) 225-3915", "link"=>"http://donnelly.house.gov/", "state"=>"IN"}]

source of the example: http://railstips.org/blog/archives/2008/07/29/it-s-an-httparty-and-everyone-is-invited/

but I fail to access the data, for example:

Representative.find_by_zip(46544).inspect["name"] returns nil

How can I access individual elements of this response?

like image 869
Victor Avatar asked May 25 '26 11:05

Victor


1 Answers

Object#inspect returns a string, not a hash. You want this:

Representative.find_by_zip(46544)['results'][0]['name']

This is what's going on: Representative#find_by_zip returns a Hash with just one index: 'results'. The item at 'results' is an array, which in this case only contains one element, so we use [0] to get the first (and only) element. That element is itself a hash that has the 'name' key, which points to the name of the first (and only) representative returned.

When you have complex hashes and arrays it's sometimes useful to format it in a more readable way to figure out how to get at the data you want:

{ "results" => [
    { "name"      => "Joe Donnelly",
      "district"  => "2",
      "office     => "1218 Longworth",
      "phone"     => "(202) 225-3915",
      "link"      => "http://donnelly.house.gov/",
      "state"     => "IN"
    }
  ]
}

That should make it more clear what's inside what here.

like image 182
Jordan Running Avatar answered May 28 '26 04:05

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!