JSON Parsing Google API Custom Search Error

2019-07-28 16:45发布

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条回答
ら.Afraid
2楼-- · 2019-07-28 17:18

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

x = Search.get('http://....').body
查看更多
登录 后发表回答