我正在尝试使用第三方客户端API在我的应用程序中获取一些信息。
网址为http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/94542。当我尝试通过OpenURI获得响应时,它会给出一种奇怪的输出:
require 'opne-uri'
require 'json'
url = 'http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/94542'
JSON.parse(open(url).read)
JSON::ParserError: 757: unexpected token at '"{\"pollenForecast\":{\"zip\":\"94542\",\"city\":\"HAYWARD\",\"state\":\"CA\",\"forecast\":[6.4,6.6,8.1,7.6],\"pp\":\" Olive and Privet.\",\"timestamp\":\"May 24, 2014 11:16:13 PM\"},\"weatherForecast\":{\"date\":\"May 27, 2014 8:06:33 AM\",\"city\":\"Hayward\",\"state\":\"CA\",\"zip\":\"94542\",\"forecast\":[{\"lowF\":56,\"highF\":68,\"iconDay\":\"3200\",\"iconNight\":\"3100\",\"skyDay\":32,\"skyNight\":31,\"phraseDay\":\"Sunny\",\"phraseNight\":\"Clear\",\"date\":\"May 24, 2014 12:00:00 AM\"},{\"lowF\":55,\"highF\":78,\"iconDay\":\"3200\",\"iconNight\":\"3100\",\"skyDay\":32,\"skyNight\":31,\"phraseDay\":\"Sunny\",\"phraseNight\":\"Clear\",\"date\":\"May 25, 2014 12:00:00 AM\"},{\"lowF\":54,\"highF\":77,\"iconDay\":\"3200\",\"iconNight\":\"3300\",\"skyDay\":32,\"skyNight\":33,\"phraseDay\":\"Sunny\",\"phraseNight\":\"Mostly Clear\",\"date\":\"May 26, 2014 12:00:00 AM\"},{\"lowF\":51,\"highF\":71,\"iconDay\":\"3000\",\"iconNight\":\"3300\",\"skyDay\":30,\"skyNight\":33,\"phraseDay\":\"Partly Cloudy\",\"phras
我如何将其解析为JSON或Ruby哈希格式。
答案 0 :(得分:2)
尝试:
json_data = ActiveSupport::JSON.decode(open(url).read)
您可能只需删除开头和结尾双引号,因此它变为:
json_data = ActiveSupport::JSON.decode(open(url).read[1..-2])
答案 1 :(得分:0)
如上所述:" Evaluate javascript on Ruby"
require 'v8'
require 'open-uri'
require 'json'
url = 'http://www.claritin.com/weatherpollenservice/weatherpollenservice.svc/getforecast/94542'
javascript = open(url).read
cxt = V8::Context.new
result = cxt.eval(javascript)
JSON.parse(result)
答案 2 :(得分:0)
Tamer's answer已关闭,但其输出将是未转义的文字:
text = open(url).read
# => "\"{\\\"pollenForecast\\\":{\\\"zip\\\":\\\"94542\\\",\\\"city\\\": ... \""
ActiveSupport::JSON.decode(text)
# => "{\"pollenForecast\":{\"zip\":\"94542\",\"city\":\"HAYWARD\",\"state\": ...}"
ActiveSupport::JSON.decode(text).class
# => String
要实际接收JSON文本作为哈希 - 您需要运行decode 两次
ActiveSupport::JSON.decode(ActiveSupport::JSON.decode(text))
# => {"pollenForecast" => {"zip" => "94542", "city" => "HAYWARD", "state" => ...}
ActiveSupport::JSON.decode(ActiveSupport::JSON.decode(text)).class
# => Hash