Search code examples
ruby-on-railsrubyjsonparsingnomethoderror

Parse Json Data with Ruby on Rails


Objective: Parse data to display all the id's in the erb file

Problem: NoMethodError in DemoController#index due to this piece of code @x = obj[i]["id"]

When I replace the "i" in the above piece of code with a number, one id number displays which leads me to believe that the while loop is correct. It just doesn't understand what "i" is.

What am I doing wrong?

Here is my code for my Controller and View

demo_controller.rb

require 'rubygems'
require 'json'
require 'net/http'
require 'httparty'
class DemoController < ApplicationController

  respond_to :json
  $angelURI = "https://api.angel.co/1/jobs"

  def index
    response = HTTParty.get('https://api.angel.co/1/jobs/')
    obj = JSON.parse(response.body)["jobs"]
    arraylength = obj.length

    i = 0
    while i <= arraylength do
      @x = obj[i]["id"]
      i += 1

    end


  end
end

index.html.erb

<%=@x%>

Solution

  • By combining best of answers we get:

    @x = []
    obj.each do |job|
      @x << job["id"]
    end