user7954 user7954 - 1 year ago 249
Ruby Question

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

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:


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("")

In routes.rb I have:

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

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:


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


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

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?

Answer Source

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:


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("").parsed_response
respond_to do |format|
   format.json { render :json => JSON.parse(@result) }
   format.html { render "index.html.erb" }

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:


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']

It just depends on your needs for the app.

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