Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove JSONP for parsing in HTTParty

I'm using Google's definition URL which returns a response stream containing JSONP data (see below).

GET http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=epitome

The response looks like this:

a({"query": "epitome", ...}, 200, null)

Before parsing the JSON, I have to strip the callback parameters; that means removing everything before the first { and everything after the last }.

I have regular expression to strip the callback parameters but am having problems using it with an HTTParty request.

Regular Expression to strip padding

^\w+\(|[^}]+$

I've tried using the following, but am getting errors.

base_url = "http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q="
word = "epitome"

request = HTTParty.get("#{base_url}#{word}").gsub(/^\w+\(|[^}]+$/)

HTTParty automatically tries to parse the data ignoring the gsub! method; so I'm not sure how to add the regexp to strip the callback parameters before HTTParty tries to parse the returned data.

Any tips on this?

like image 639
Kyle Avatar asked Dec 15 '22 02:12

Kyle


1 Answers

Use a custom parser. In this example, I use a substring to strip off the padding, but you could use a regex if you prefer:

require 'httparty'

class JsonpParser < HTTParty::Parser
  SupportedFormats = {"text/javascript" => :jsonp}

  def jsonp
    JSON.load(body[2..-11], nil)
  end

end

class Dictionary
  include HTTParty

  parser JsonpParser

  def self.define(word)
    get "http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=#{word}"
  end

end

Dictionary.define 'epitome'
like image 137
Jimothy Avatar answered Dec 30 '22 03:12

Jimothy