user7954
user7954

Reputation: 323

How do I get and display JSON with HTTParty?

I'm new to Ruby on Rails and programming in general. So far I've successfully used my console to return JSON data from an API but I can't seem to make it work on my local server.

In the console I entered:

httparty "http://rubygems.org/api/v1/versions/httparty.json" 

and it returned the JSON after I managed to install/configure everything.

So then in the console I wrote:

rails new Catalog
rails generate controller new index

I followed the tutorial to get <h1>Hello, Rails!</h1> to display on my page when I go to:

http://localhost:3000/

Now I am trying to get the JSON data returned and display on that same page where it says "Hello, Rails".

In index.html.erb I have:

<h1>Hello, Rails</h1>
<%= @result %>

In home_controller.rb I have:

class HomeController < ApplicationController
  def get_catalog
  include HTTParty
  @result = HTTParty.get("http://rubygems.org/api/v1/versions/httparty.json")
  end
end

In routes.rb I have:

Catalog::Application.routes.draw do
  get "home/index"
  root :to => 'home#index'
end

Nothing appears under "Hello, Rails" when I go to the page.

I'm still trying to wrap my head around how all of this stuff interacts with each other. Can anyone see what I'm doing wrong here perhaps?

--- Update I'm trying to output just the product names into li elements. My files now are:

index.html.erb:

<ul>
  <% @http_party_json.each do |event| %>
      <% event.each do |e| %>
          <li><%=h e['Products']['Name'] %></li>
      <% end %>
  <% end %>
</ul>

controller:

class HomeController < ApplicationController
  def index
    @response =     HTTParty.get("myURL")
    @http_party_json = JSON.parse(@response.body)
  end
end

The error I am getting is:

undefined method `[]' for nil:NilClass
Extracted source (around line #5):

2: <ul>
3:   <% @http_party_json.each do |event| %>
4:       <% event.each do |e| %>
5:           <li><%=h e['Products']['Name'] %></li>
6:       <% end %>
7:   <% end %>
8: </ul>

When I take off the ['Name'] I get JSON starting with:

[{"Name"=>"3x4 Vinyl Magnet", "Description"=>"Made of durable high-gloss vinyl.  Measures 3x4 inches and has rounded corners. Waterproof and scratch resistant."

Why can't I target ['Name'] to get just the product names?

Upvotes: 1

Views: 7793

Answers (2)

Joe Edgar
Joe Edgar

Reputation: 940

HTTParty.get returns an object of the type HTTParty::Response, which is documented in HTTParty (Check out the examples.)

There is a nice helper method on HTTParty::Response called `#parsed_response. This returns the JSON string parsed into a Hash or Array:

HTTParty.get("URL").parsed_response

Alternatively, in order to get the body of this message, you can call @result.body. This returns a string, which you can safely output to your page as you did. However, I'm guessing you want to do more with it than just output it to a page.

In order to parse this into a hash/Array that you can use/manipulate/return as true JSON you would do something like:

http_party_json = JSON.parse(@response.body)

So with this, you could do something like the following in your controller if you wanted to be able to return JSON:

@response = HTTParty.get("http://rubygems.org/api/v1/versions/httparty.json").parsed_response
respond_to do |format|
   format.json { render :json => JSON.parse(@result) }
   format.html { render "index.html.erb" }
end

Updated answer based on your updated information:

It appears as though e['Products'] returns an array (notice the square brackets on the outside.) So, if you are only expecting one you could do:

e['Products'][0]['Name'] 

If it might return multiple products, you might, instead, need to account for the possibility of many products and use an each block:

e['Products'].each do |product|
    #do something with product['Name']
end

It just depends on your needs for the app.

Upvotes: 3

Mark Thomas
Mark Thomas

Reputation: 37507

HTTParty parses XML/JSON responses for you. Simply use parsed_response to get it:

@response = HTTParty.get("URL").parsed_response

Upvotes: 6

Related Questions