Reputation: 3500
I have the following hash:
{
"groups" => [
{
"type" => "Nearby",
"venues" => [
{
"id" => 4450132,
"name" => "Position2",
"address" => "Domlur",
"city" => "Bangalore",
"state" => "Karnataka/India",
"zip" => "560037",
"verified" => false,
"geolat" => 12.9566921,
"geolong" => 77.6407258,
"stats" => {
"herenow" => "0"
},
"twitter" => "position2",
"hasTodo" => "false",
"distance" => 0
},...
I want to iterate through it and find all the 'name' attributes. My code looks like:
response["groups"]["Nearby"]["venues"].each do |key|
logger.debug key['name']
end
But I keep on getting error:
TypeError (can't convert String into Integer):
I am on ruby 1.9.
Upvotes: 0
Views: 419
Reputation: 160551
If I clean up the hash so it's properly balanced:
data = {
"groups" => [
{
"type" => "Nearby",
"venues" => [
{
"id" => 4450132,
"name" => "Position2",
"address" => "Domlur",
"city" => "Bangalore",
"state" => "Karnataka/India",
"zip" => "560037",
"verified" => false,
"geolat" => 12.9566921,
"geolong" => 77.6407258,
"stats" => {
"herenow" => "0"
},
"twitter" => "position2",
"hasTodo" => "false",
"distance" => 0
}
]
}
]
}
I can iterate over the hash finding the 'name'
keys using:
data['groups'].map{ |i| i['venues'].map{ |j| j['name'] } } # => [["Position2"]]
Because the data is nested, the resulting extracted data will be nested. To flatten it use flatten
:
data['groups'].map{ |i| i['venues'].map{ |j| j['name'] } }.flatten # => ["Position2"]
Upvotes: 1
Reputation: 12243
use this:
response["groups"][0]["venues"].each do |key|
logger.debug key['name']
end
The reason is that your response["groups"] object is actually an array and not a map.
Upvotes: 1
Reputation: 370122
response["groups"]
is an Array. Arrays are indexed by integers, not strings.
If you want to get the group, whose type is "Nearby" you can use:
response["groups"].find {|h| h["type"] == "Nearby}["venues"].each ...
Upvotes: 3