Jump to content

The ultimate community for Ruby on Rails developers.


Photo

How to work with JSON data after API request?


  • Please log in to reply
1 reply to this topic

#1 dutchM

dutchM

    Passenger

  • Members
  • 4 posts

Posted 08 December 2013 - 05:24 PM

Hello all,

 

I'm new to programming and I decided to try to learn ruby on rails as my first major language. The main reason I'm doing this is because my dad has a business he wants to start and I would like to be involved in it. Anyway, so far I have successfully returned JSON using HTTParty but now I am struggling on how to work with it.

 

I am targeting a catalog URL that returns product information.

 

My controller:

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

My index.html.erb:

<ul>
  <% @http_party_json.each do |event| %>
      <% event.each do |e| %>
          <li><%=h e %></li>
      <% end %>
  <% end %>
</ul>

This outputs the following when I go to my localhost:3000 page:

<li>Status</li>
<li>{"Code"=>200, "Description"=>"Success"}</li>
<li>Catalog</li>
<li>{"GenerationDateTime"=>"2012-04-09T13:15:43-04:00", "DeliveryMethods"=>[{"ServiceType"=>"MailOrder"}], "Products"=>[{"Name"=>"3x4 Vinyl Magnet", "Description"=>"Made of durable high-gloss vinyl. Measures 3x4 inches and has rounded corners. Waterproof and scratch resistant.",...</li>

What I really want to do is target all of the product names and output them into a catalog type fashion on my html page. Eventually I would be outputting a lot of the information from this json to build a catalog of products to display.

 

When I try to do: <%=h e['Products'] %> instead I get:

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

So I figured doing <%=h e['Products']['Name'] %> would let me get the product names but I get the following error:

 

undefined method `[]' for nil:NilClass

 

Hoping someone can help me understand how to work with the json data after I have captured it, thank you!



#2 Kelli Shaver

Kelli Shaver

    Inspector

  • Administrators
  • 75 posts
  • LocationKentucky

Posted 09 December 2013 - 04:14 AM

Well, look at your parsed JSON data.

[{"Name"=>"3x4 Vinyl Magnet", "Description"=>"Made of durable high-gloss vi....

Products is an array. You need to use:

e["Products"][0]["Name"]

If you want info for more than the first product, you'll need to iterate through the array. 






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users