2017-08-15 40 views
0

我開始學習Ruby on Rails和我有一個看起來像這樣JSON數據:如何在Rails中輸出JSON特定值

{ 
    "page": 1, 
    "total_results": 19601, 
    "total_pages": 981, 
    "results": [ 
     { 
     "vote_count": 4064, 
     "id": 211672, 
     "video": false, 
     "vote_average": 6.4, 
     "title": "Minions", 
     "popularity": 197.218355, 
     "poster_path": "/q0R4crx2SehcEEQEkYObktdeFy.jpg", 
     "original_language": "en", 
     "original_title": "Minions", 
     "genre_ids": [ 
      10751, 
      16, 
      12, 
      35 
     ], 
     "backdrop_path": "/uX7LXnsC7bZJZjn048UCOwkPXWJ.jpg", 
     "adult": false, 
     "overview": "Minions Stuart, Kevin and Bob are recruited by Scarlet Overkill, a super-villain who, alongside her inventor husband Herb, hatches a plot to take over the world.", 
     "release_date": "2015-06-17" 
     }, 
     { 
     "vote_count": 4526, 
     "id": 321612, 
     "video": false, 
     "vote_average": 6.8, 
     "title": "Beauty and the Beast", 
     "popularity": 106.789987, 
     "poster_path": "/tWqifoYuwLETmmasnGHO7xBjEtt.jpg", 
     "original_language": "en", 
     "original_title": "Beauty and the Beast", 
     "genre_ids": [ 
      10751, 
      14, 
      10749 
     ], 
     "backdrop_path": "/6aUWe0GSl69wMTSWWexsorMIvwU.jpg", 
     "adult": false, 
     "overview": "A live-action adaptation of Disney's version of the classic 'Beauty and the Beast' tale of a cursed prince and a beautiful young woman who helps him break the spell.", 
     "release_date": "2017-03-16" 
     }, 
//snipped rest of JSON for brevity 

,我想只打印出「冠軍 「從每個」結果「。

模式

class ModelForMyApi < ActiveRecord::Base 
require 'rest_client' 

    @url 

    def self.getData 
     response = RestClient(@url, { :content_type => :json, "Api-Key" => "put your API key here" } 
    end 

    def self.retrieve_results(myParameter) 
     @url = "myApiUrl.com/stuff/?putYourParamNameHere=#{myParameter}" 
     JSON.parse(ModelForMyApi.getData) 
    end 
end 

而且控制器

class ExamplesController < ApplicationController 
    def index 
     @results = ModelForMyApi.retrieve_results("superCoolParameter") 
    end 
end 

我怎麼會打印出所有的 「標題」?我不確定我是否正在迭代並正確訪問JSON。 我該怎麼辦:

<% @results['results'].each do |t| %> 
<%= t['title'] %> 

謝謝!

+0

@Jason你沒有得到你期望的結果嗎?它看起來像你的代碼應該工作 –

回答

0
<% @results['results'].each do |t| %> 
    <%= t['title'] %> 
<% end %> 

您的代碼沒問題。只要不要忘記<%end%>關閉該塊。

相關問題