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?
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.
To Access the individual elements, You can use:-
If the response is JSON:- You can use:-
response.parsed_response["key"]
If your response is a string then, you can use:-
data = JSON.parse(resp.body)
The response type depends, on the content type you are setting while requesting the data:-
'Content-Type' => 'application/json'
If you don't set the content type it returns response as string.
精彩评论