2016-10-22 75 views
0

我目前正在嘗試在連接到OMBD API的Ruby on Rails中構建一個簡單的Web應用程序。我是Ruby的新手和一般編碼。我試圖運行一個FOR循環來收集搜索查詢中的所有標題。這裏是我的方法從我查看簡單的API調用來解析JSON

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 

代碼:

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

我正試圖運行應用程序時出現以下錯誤:

散列的隱式轉換成數組

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

任何人都可以幫忙嗎?

回答

0

您得到的回覆不是散列。它是一組哈希值。請嘗試打印出responsebody [0]。

responsebody = [{}, {}] 

我猜你的迴應正文與上面的代碼一樣。調用reponsebody [0]將取出數組中的第一個元素(即您需要的響應哈希)。

+0

這是一個將要進行的呼叫的示例: –

+0

{「Search」:[{「Title」:「Grand Budapest Hotel」,「Year」:「2014」,「imdbID」:「tt2278388」} ],「totalResults」:「1095」,「Response」:「True」} –

+0

所以我相信這是一個散列,並且存在一個嵌套在散列中的數組,然後在數組中存在多重散列。任何想法如何從這個JSON響應中提取所有哈希? –