JSON Parsing Google API Custom Search Error

折月煮酒 提交于 2019-12-24 08:28:08

问题


I have the following code:

require 'rubygems'
require 'httparty'
require 'pp'
require 'json'

class Search
  include HTTParty
  format :json
end


x = Search.get('https://www.googleapis.com/customsearch/v1key=AI...&cx=013...=flowers&alt=json')
x = x.to_s

result = JSON.parse(x)

And every time I run it on the google search results that come back I get the following:

FlowerPlaces.com Delivers Fresh <b>Flowers</b> To Your Place! <br>  
Order <b>Flowers</b> Online or Call 800-411-9049 for Same Day <b>Flower</b> 
Delivery.", "cacheId"=>"v94CIDza4gQJ"}]}' (JSON::ParserError)
from /usr/local/lib/ruby/1.9.1/json/common.rb:148:in `parse'
from gg.rb:15:in `<main>'

Here is that same line in the string version which JSON is trying to parse:

Order <b>Flowers</b> Online or Call 800-411-9049 for Same Day <b>Flower</b> 
Delivery.\", \"cacheId\"=>\"v94CIDza4gQJ\"}]}"

Now, I've tried it with multiple search quires and I'm wondering am I doing something wrong? I added to the .to_s because the json parser tries to convert the HTTParty get statement to a string and can't and then throws an error. The JSON parser appears to get all the way to the end of the string (which is everything google has returned to me) before it throws the error.

What am I missing?


回答1:


You need to add .body onto the end of the x = Search.get('http://....') like so:

x = Search.get('http://....').body


来源:https://stackoverflow.com/questions/8173962/json-parsing-google-api-custom-search-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!