Merge pull request #2532 from hasclass/as_json__encode_infinite_and_nan_floats_as_null

JSON: Encode infinite or NaN floats as `null` to generate valid JSON.
This commit is contained in:
Piotr Sarnacki 2012-04-30 21:06:22 -07:00
commit 3cc6995e71
2 changed files with 7 additions and 0 deletions

@ -182,6 +182,10 @@ def as_json(options = nil) self end #:nodoc:
def encode_json(encoder) to_s end #:nodoc:
end
class Float
def as_json(options = nil) finite? ? self : NilClass::AS_JSON end #:nodoc:
end
class BigDecimal
# A BigDecimal would be naturally represented as a JSON number. Most libraries,
# however, parse non-integer JSON numbers directly as floats. Clients using

@ -27,6 +27,9 @@ def as_json(options)
NilTests = [[ nil, %(null) ]]
NumericTests = [[ 1, %(1) ],
[ 2.5, %(2.5) ],
[ 0.0/0.0, %(null) ],
[ 1.0/0.0, %(null) ],
[ -1.0/0.0, %(null) ],
[ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],