'JSON.parse'错误处理无效/非JSON格式

时间:2018-06-12 03:10:17

标签: ruby

我从HTTP流媒体服务请求信息。它以JSON格式提供数据。这是the documentation。这是我正在使用的代码的一部分:

require 'uri'
require 'net/https'
require 'json'


uri = URI("https://api.tradier.com/v1/markets/events/session")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
http.read_timeout = 30
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

# Headers

request["Accept"] = "application/json"
request["Authorization"] = "Bearer xxx"

# Send synchronously

response = http.request(request)

# parses response

parse = JSON.parse(response.body)

#out puts values only from response

sessionid = parse.values[0]["sessionid"]
url = parse.values[0]["url"]


uri = URI("#{url}?sessionid=#{sessionid}&symbols=aapl")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
http.read_timeout = 30
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER

# Headers

request["Accept"] = "application/json"
request["Authorization"] = "Bearer xxx"


http.request request do |response|
  response.read_body do |data|
    puts data.class
  #  info = JSON.parse(data, :quirks_mode => true)
  #  puts info.values
    end
end

我希望系统继续该程序。我似乎需要使用beginrescue,但我无法让它们发挥作用。当我请求数据时,我收到以下错误:

  

`parse':757:'{“类型”:“trade”,“symbol”的意外标记:“AAPL”,“exch”:“Q”,“price”:“191.23”,“size”: “1081622”, “CVOL”: “18308460”, “日期”: “1528747200000”, “最后的”: “191.23”} { “类型”: “摘要”, “符号”: “AAPL”, “开放”:” 191.35“,”high“:”191.97“,”low“:”190.21“,”prevClose“:”191.7“,”close“:”191.23“}'(JSON :: ParserError)

1 个答案:

答案 0 :(得分:2)

您使用的终端记录在Tradier API docs中,它是streaming endpoint

似乎响应不会被分块,每个块只包含一个JSON文档。但是看起来文件被换行符分开,使得响应看起来像:

{ "json": "data" }
{ "more": "data" }

这不是有效的JSON。您可能需要通过执行以下操作逐个解析它们:

http.request request do |response|
  response.read_body do |data|
    data.each_line do |chunk|
      info = JSON.parse(chunk)
      puts info.inspect
    end
  end
end

如果响应分块发生在JSON文档的中间,则必须使用某种缓冲读取器。