質問

I'm using HTTParty to make calls to an API. When I have callback in the url it causes MultiJson::DecodeError:

MultiJson::DecodeError in PagesController#home

756: unexpected token at '12345({"label":"daydata","data":[[1335484800883,69586],
[1335571201001,17725]]});

My get call looks like this:

@data = HTTParty.get("http://powermeters.appspot.com/getdays?id=1234567890&from=2012-04-24&to=2012-04-29&callback=12345")

Does anyone know what is causing this, and how to solve it?

役に立ちましたか?

解決

The problem is that the response is javascript, not JSON. To fix it you can do:

response.gsub! /^\d+\((.*)\);?$/m, '\\1'

or something similar.

他のヒント

You can also override the parser. A simple example is below.

The if MultiJson... is pulled straight from HTTParty's json parser

class Foo
  include HTTParty
  base_uri "http://foo.bar"

  parser lambda { |body,_|
    new_body = body.gsub(/^\d+\((.*)\)$/, '\1')
    if MultiJson.respond_to?(:adapter)
      MultiJson.load(new_body)
    else
      MultiJson.decode(new_body)
    end
  }
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top