Accessing data from httparty response
ruby-on-rails
Solution
`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.
Problem
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?