如何在Rails中从JSON输出特定值

时间:2017-08-15 17:47:16

标签: ruby-on-rails json ruby

我开始学习Ruby on Rails并且我有JSON数据,如下所示:

while true; do
    echo "What command would like to run?"
    read command
    case "$command" in
        "my-tweets" | "do-what-it-says")
            node liri.js "$command" ;;

        "spotify-this-song" | "movie-this")
            echo What item would like to query?
            read item
            node liri.js "$command" "$item" ;;

        "end")
            break ;;

        *)
            echo "Unknown command: $command" ;;
    esac
done

我想从每个“结果”中打印出“标题”。

我的模型

{
   "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

我如何打印出所有“标题”?我不确定我是否正在迭代并正确访问JSON。 我这样做:

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

你的代码很好。只是不要忘记&lt;%end%&gt;关闭街区。