mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Fix an issue with JSON encoding of "Infinity" and "NaN" values
- When `as_json` returns `Infinity` or `NaN` as the value of any of the key, we don't used to call `as_json` on it as it was treated as primitive. - This used to pass `Infinity` or `NaN` to `JSON.generate` and Ruby used to throw an error for `Infinity/NaN not allowed in JSON.` - This patch changes the code to call `as_json` on these primitives so that they are converted to proper values before being passed to `JSON.generate`. - Fixes #26877.
This commit is contained in:
parent
fe1f4b2ad5
commit
8776f15b44
2 changed files with 23 additions and 1 deletions
|
@ -84,7 +84,7 @@ module ActiveSupport
|
||||||
when String
|
when String
|
||||||
EscapedString.new(value)
|
EscapedString.new(value)
|
||||||
when Numeric, NilClass, TrueClass, FalseClass
|
when Numeric, NilClass, TrueClass, FalseClass
|
||||||
value
|
value.as_json
|
||||||
when Hash
|
when Hash
|
||||||
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
|
Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }]
|
||||||
when Array
|
when Array
|
||||||
|
|
|
@ -432,6 +432,28 @@ EXPECTED
|
||||||
assert_equal '"foo"', ActiveSupport::JSON.encode(exception)
|
assert_equal '"foo"', ActiveSupport::JSON.encode(exception)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
class InfiniteNumber
|
||||||
|
def as_json(options = nil)
|
||||||
|
{ "number" => 1.0 / 0 }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_to_json_works_when_as_json_returns_infinite_number
|
||||||
|
expected = { number: nil }.to_json
|
||||||
|
assert_equal expected, InfiniteNumber.new.to_json
|
||||||
|
end
|
||||||
|
|
||||||
|
class NaNNumber
|
||||||
|
def as_json(options = nil)
|
||||||
|
{ "number" => 0.0 / 0 }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_to_json_works_when_as_json_returns_NaN_number
|
||||||
|
expected = { number: nil }.to_json
|
||||||
|
assert_equal expected, NaNNumber.new.to_json
|
||||||
|
end
|
||||||
|
|
||||||
protected
|
protected
|
||||||
|
|
||||||
def object_keys(json_object)
|
def object_keys(json_object)
|
||||||
|
|
Loading…
Reference in a new issue