Bryan Bryan - 6 months ago 42
Ruby Question

Rails returns invalid JSON when rendering hash containing Float::NAN objects

I'm returning JSON for a Rails controller call. In the controller, I need to generate JSON from a Ruby hash, which contains NaN objects. The browser shows an error when the JSON is returned:

{
"value": NaN
}



Error: Parse error on line 1: "value": NaN


I did some quick research and it seems that NaN is not a valid JSON object, thus should be wrapped in quotes - "NaN". It seems pretty dumb that Rails JSON parser doesn't conform to standard JSON format and wraps the NaN object in quotes.

I've tried to flatten the hash to a string and convert it back to a hash. But I've been consistently getting parse errors.

How do I get around this?




EDIT:

To simply the problem, the hash looks like this:

{ "value" => Float::NAN }





EDIT 2:

I need to convert the above hash to the following json:

{
"value": "NaN"
}

Answer

Ah I figured it out - this was fixed about 10 months ago in the Rails main branch. (https://github.com/rails/rails/commit/7b53d1372df4bbc7a539b5e493ff1491ec460397)

To fix it for your Rails 3.2.3 <, simply add the following code:

class Float
  def as_json(options = nil) finite? ? self : NilClass::AS_JSON end #:nodoc:
end
Comments