簡體   English   中英

如何在Rails中從JSON輸出特定值

[英]How to output specific values from JSON in Rails

我開始學習Ruby on 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'] %>

謝謝!

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

您的代碼很好。 只是不要忘記<%end%>來關閉該塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM