如何从API中提取从哈希数组返回的数据

时间:2017-02-05 19:45:38

标签: ruby nokogiri

我写了一个小程序来与Indeed Ruby API进行交互。

我可以打印一个职位,但是想要全部循环。

以下是代码:

require 'nokogiri'
require 'indeed-ruby'

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

params = {
  :q => 'python',
  :l => 'vancouver',
  :userip => '1.2.3.4',
  :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"]
end

each循环返回此错误消息:

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

我认为此错误消息是说它试图找到一个整数,我在["results"]["jobtitle"]中放置一个字符串。

此行有效,并打印职位名称:

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

这意味着我可以访问结果哈希的第0个元素,然后访问jobtitle属性。

我希望循环像这样运行并打印3个职称:

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

我不确定如果[i]计数器需要一个整数,如何将它放在循环中。

以下是从Indeep API返回的数据:

{"version"=>2,
 "query"=>"python",
 "location"=>"vancouver",
 "paginationPayload"=>"",
 "radius"=>25,
 "dupefilter"=>true,
 "highlight"=>true,
 "totalResults"=>483,
 "start"=>1,
 "end"=>10,
 "pageNumber"=>0,
 "results"=>
  [{"jobtitle"=>"Junior Software Developer",
    "company"=>"LaunchCode",
    "city"=>"Portland",
    "state"=>"OR",
    "country"=>"US",
    "formattedLocation"=>"Portland, OR",
    "source"=>"LaunchCode",
    "date"=>"Fri, 03 Feb 2017 04:10:27 GMT",
    "snippet"=>
     "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?...",
    "url"=>
     "http://www.indeed.com/viewjob?jk=9f75f0ea8825e3a8&qd=X0KuMlb--hp3Z0o2UU7dJOXoIlOcgm8VSZO61KKa0UOtGpLfFk1WY111OhfFWzZjMBRv9LrdGhB8olLNQGabmQRFit3-lRPP9j12GNvnf88&indpubnum=4334069173238194&atk=1b87s51b1a0kqb7s",
    "onmousedown"=>"indeed_clk(this,'782');",
    "jobkey"=>"9f75f0ea8825e3a8",
    "sponsored"=>false,
    "expired"=>false,
    "indeedApply"=>false,
    "formattedLocationFull"=>"Portland, OR",
    "formattedRelativeTime"=>"2 days ago",
    "stations"=>""},

看起来来自Indeed API的响应是一个哈希值,但&#34;的结果是&#34; key是哈希中的数组。

以下来自Ursus的回复有效:

这也有效:

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

这是输出:

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

1 个答案:

答案 0 :(得分:1)

所以,data["results"]是一个数组。在ruby中,您不需要索引来遍历数组。你可以做点什么

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

在你的情况下,

data["results"].each do |item|
  puts item["jobtitle"]
end