Skip to content
Browse files

Merge pull request #2532 from hasclass/as_json__encode_infinite_and_n…

…an_floats_as_null

JSON: Encode infinite or NaN floats as `null` to generate valid JSON.
  • Loading branch information...
2 parents cb5b0cf + 7b53d13 commit 3cc6995e714bc763b40eb3e1d710c1e5ded44384 @drogus drogus committed Apr 30, 2012
Showing with 7 additions and 0 deletions.
  1. +4 −0 activesupport/lib/active_support/json/encoding.rb
  2. +3 −0 activesupport/test/json/encoding_test.rb
View
4 activesupport/lib/active_support/json/encoding.rb
@@ -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
View
3 activesupport/test/json/encoding_test.rb
@@ -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")],

0 comments on commit 3cc6995

Please sign in to comment.
Something went wrong with that request. Please try again.