Ryan Sudding Ryan Sudding - 1 year ago 98
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
response = HTTParty.get(url)
responsebody = JSON.parse(response.body)
return allresponses []

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 Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download