1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

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

View file

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

View file

@ -27,6 +27,9 @@ class TestJSONEncoding < ActiveSupport::TestCase
NilTests = [[ nil, %(null) ]] NilTests = [[ nil, %(null) ]]
NumericTests = [[ 1, %(1) ], NumericTests = [[ 1, %(1) ],
[ 2.5, %(2.5) ], [ 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}") ]] [ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")], StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],