2017-08-15 18 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%>关闭该块。

相关问题