Ryan Sudding Ryan Sudding - 1 month ago 11
Ruby Question

Simple API call to parse JSON

I am currently trying to build a simple web application in Ruby on Rails connecting to the OMBD api. I am new to Ruby and coding in general. I am trying to run a FOR loop to collect all the titles from a search query. Here is my method

def self.findAllTitles(title)
allresponses = []
for page in 1..100 do
url="http://www.omdbapi.com/?s=#{title}&page=#{page}"
response = HTTParty.get(url)
responsebody = JSON.parse(response.body)
allresponses.concat(responsebody)
end
return allresponses []
end


Code from my View:

<% @responsealltitles.each do |result| %>
<td><%= result["Title"] %></td>
<td><%= result["Year"] %></td>


I am getting the following error when trying to run the application:

no implicit conversion of Hash into Array

Extracted source (around line #11):
puts responsebody = JSON.parse(response.body)

Can anyone help?

Answer

The response you get is not a hash. It is an array of hashes. Please try printing out responsebody[0].

responsebody = [{}, {}]

I guess your response body is as above code. Calling reponsebody[0] will take out the first element in the array(that is the response hash you need).

Comments