I'm using the Bandsintown api to grab upcoming concert dates based on which artists a user is following on my site and where the user is located. Right now I'm having trouble iterating over a multidimensional array of data that I get back as a response.
The Goal
To iterate through an array of arrays and then grab an artists' name to display it on my view.
I'm able to grab the data I want with the following code inside my controller:
class CalendarController < ApplicationController
require 'uri'
def index
@user = current_user
@hash_version_array = []
@user.follows.each do |follow|
response = HTTParty.get("http://api.bandsintown.com/artists/#{URI.escape(follow.artist_name)}/events/search.json?api_version=2.0&app_id=el_proyecto_de_la_musica&location=use_geoip")
@hash_version = JSON.parse(response.body)
@hash_version_array << @hash_version
end
@hash_version_array
end
def show
end
end
the code above produces the following results inside of my @hash_version_array (click here for the results, easier to show through a gist on github)
I get stuck when trying to iterate over @hash_version_array to grab each artist's name.
Attempt 1
[9] pry(#<CalendarController>)> @hash_version_array.each do |sub_array|
[9] pry(#<CalendarController>)* sub_array.each do |artist|
[9] pry(#<CalendarController>)* artist["artists"]["name"]
[9] pry(#<CalendarController>)* end
[9] pry(#<CalendarController>)* end
Results in
TypeError: no implicit conversion of String into Integer
from (pry):96:in `[]'
Attempt 2
[8] pry(#<CalendarController>)> @hash_version_array.each do |sub_array|
[8] pry(#<CalendarController>)* sub_array.each do |artist|
[8] pry(#<CalendarController>)* artist["artists"].each do |artist|
[8] pry(#<CalendarController>)* artist["name"]
[8] pry(#<CalendarController>)* end
[8] pry(#<CalendarController>)* end
[8] pry(#<CalendarController>)* end
Results in the same value I got for @hash_version_array to begin with
To get the name of an artist, you'll have to fetch it via the following structure:
artist[0]["artists"][0]["name"]
I'll leave it up to you to make the code more robust.
A Hash is a dictionary-like collection of unique keys and their values
hash = {my_key: my_value}
so if you want to get a value
just use hash['my_key']
docs
hash.each do |key,value|
key['my_key']
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.