0

我正在尝试编写一个简单的程序来从 API 调用的结果中解析 JSON。对红宝石非常陌生,只是无法弄清楚这一点。

这是所有代码:

require "rubygems"
require "json"
require "net/http"
require "uri"

uri = URI.parse("http://api.chartbeat.com/live/recent/v3/?apikey=eaafffb9a735796b6edd50fd31eaab69&host=enactus.org")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)

response = http.request(request)

if response.code == "200"
  result = JSON.parse(response.body)

  result.each do |doc|
    puts doc["id"] #reference properties like this
    puts doc # this is the result in object form    
    puts ""
    puts ""
  end
else
  puts "ERROR!!!"
end

这是运行程序的输出(chartbeat.rb):

chartbeat.rb:14: syntax error, unexpected end-of-input, expecting keyword_end

该程序从这里逐字逐句替换了网址:https ://gist.github.com/timsavery/1657351

4

1 回答 1

0

看起来您正在做的事情并没有利用 Net::HTTPS 的任何功能,所以我可能会这样做:

require "rubygems"
require "json"
require "open-uri"

response = open("http://api.chartbeat.com/live/recent/v3/?apikey=eaafffb9a735796b6edd50fd31eaab69&host=enactus.org").read

result = JSON.parse(response)

result.each do |doc|
  puts doc["id"] #reference properties like this
  puts doc # this is the result in object form
  puts ""
  puts ""
end

OpenURI 是许多访问 URL 的代码的基础,是一个很好的起点。

如果要捕获引发的异常,请使用以下内容:

begin
  response = open("http://api.chartbeat.com/live/recent/v3/?apikey=eaafffb9a735796b6edd50fd31eaab69&host=enactus.org").read
rescue Exception => e
  puts e.message
  exit
end

它甚至可以简化为:

require "rubygems"
require "json"
require "open-uri"

JSON[
  open("http://api.chartbeat.com/live/recent/v3/?apikey=eaafffb9a735796b6edd50fd31eaab69&host=enactus.org").read
].each do |doc|
  puts doc["id"] #reference properties like this
  puts doc # this is the result in object form
  puts ""
  puts ""
end

但这可能太激烈了。

于 2013-09-13T22:42:19.593 回答