DanHodgins DanHodgins - 4 years ago 108
Ruby Question

How to extract data returned from array of hashes from API

I wrote a small program to interact with the Indeed Ruby API.

I can print a single job title, but would like to loop through them all.

Here is the code:

require 'nokogiri'
require 'indeed-ruby'

client = Indeed::Client.new ("PUBLISHER_KEY_GOES_HERE")

params = {
:q => 'python',
:l => 'vancouver',
:userip => '',
:useragent => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)',
:jobkeys => ["JOB_KEY_A", "JOB_KEY_B"]

data = client.search(params)

# loop through all results and print the job title
data.each do |d|
puts d["results"]["jobtitle"]

loop returns this error message:

i.rb:23:in `[]': no implicit conversion of String into Integer (TypeError)
from i.rb:23:in `block in <main>'
from i.rb:22:in `each'
from i.rb:22:in `<main>'

I assume this error message is saying it's trying to find an integer where I am putting a string in either

This line works, and prints a job title:

puts data["results"][0]["jobtitle"]

This implies I can access the 0th element of the results hash, and then access the jobtitle attribute.

I want to the loop to run like this and print 3 job titles:

puts data["results"][0]["jobtitle"]
puts data["results"][1]["jobtitle"]
puts data["results"][2]["jobtitle"]

I'm not sure how to put an
counter in the loop if it's expecting an integer.

Here is what the data looks like coming back from the Indeep API:

[{"jobtitle"=>"Junior Software Developer",
"formattedLocation"=>"Portland, OR",
"date"=>"Fri, 03 Feb 2017 04:10:27 GMT",
"Familiarity with an at least one imperative (Java, JavaScript, PHP, C#, Objective-C, C/C++, <b>Python</b>, Ruby, etc.). Don’t have a CS degree?...",
"formattedLocationFull"=>"Portland, OR",
"formattedRelativeTime"=>"2 days ago",

It looks like the response from the Indeed API is a hash, but the value for the "results" key is an array inside the hash.

The response below from Ursus works:

This also worked:

for i in 1...10
puts data["results"][i]["jobtitle"]

Here is the output:

Junior Software Developer
Data Scientist
Python Developer
Python Automation Developer - Hillsboro, OR
Computer Vision Engineer
Python Web Engineer
EMS Network Applications Engineer II
Software Engineer
Python Developer (full-stack)
Electrical Engineer, EMS Network Applications

Answer Source

So, data["results"] is an array. In ruby, you don't need an index to go through an array. You can do something like

[1, 2, 3].each do |i|
  puts i

In your case,

data["results"].each do |item|
  puts item["jobtitle"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download