Jason Jason -3 years ago 84
Ruby Question

How to output specific values from JSON in Rails

I'm starting to learn Ruby on Rails and I have JSON data that looks like this:

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


and I want to only print out the "title" from each "result."

My model is

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


And controller is

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


How would I print out all the "titles"? I'm not sure I'm iterating and accessing the JSON correctly.
Do I do:

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


Thanks!

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

Your code is fine. Just do not forget the <% end %> to close the block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download