Bryan Bryan - 2 years ago 138
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?


To simply the problem, the hash looks like this:

{ "value" => Float::NAN }


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

"value": "NaN"

Answer Source

Ah I figured it out - this was fixed about 10 months ago in the Rails main branch. (

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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download