Skip to content

Commit

Permalink
Merge pull request rails#6096 from hasclass/as_json__encode_infinite_…
Browse files Browse the repository at this point in the history
…and_nan_bigdecimals_as_null

JSON: encode BigDecimal NaN/Infinity as null.
  • Loading branch information
drogus committed May 1, 2012
2 parents 7d2df5f + d538778 commit ec94d84
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
4 changes: 3 additions & 1 deletion activesupport/lib/active_support/json/encoding.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ def encode_json(encoder) to_s end #:nodoc:
end

class Float
# Encoding Infinity or NaN to JSON should return "null". The default returns
# "Infinity" or "NaN" what breaks parsing the JSON. E.g. JSON.parse('[NaN]').
def as_json(options = nil) finite? ? self : NilClass::AS_JSON end #:nodoc:
end

Expand All @@ -195,7 +197,7 @@ class BigDecimal
# That's why a JSON string is returned. The JSON literal is not numeric, but if
# the other end knows by contract that the data is supposed to be a BigDecimal,
# it still has the chance to post-process the string and get the real value.
def as_json(options = nil) to_s end #:nodoc:
def as_json(options = nil) finite? ? to_s : NilClass::AS_JSON end #:nodoc:
end

class Regexp
Expand Down
1 change: 1 addition & 0 deletions activesupport/test/json/encoding_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def as_json(options)
[ 0.0/0.0, %(null) ],
[ 1.0/0.0, %(null) ],
[ -1.0/0.0, %(null) ],
[ BigDecimal('0.0')/BigDecimal('0.0'), %(null) ],
[ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]

StringTests = [[ 'this is the <string>', %("this is the \\u003Cstring\\u003E")],
Expand Down

0 comments on commit ec94d84

Please sign in to comment.