diff --git a/CHANGES.md b/CHANGES.md index 55266e9c..ccffd169 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,8 @@ ### Unreleased +* Properly raise `JSON::GeneratorError` instead of `NoMethodError` when encountering duplicate keys in rfc8785 mode. + ### 2026-11-24 (3.2.0) * The `script_safe: true` option of `JSON.generate` no longer escapes forward slashes `/`, and instead escapes script tag diff --git a/lib/json/ext.rb b/lib/json/ext.rb index 75d0e4e3..4de400bc 100644 --- a/lib/json/ext.rb +++ b/lib/json/ext.rb @@ -44,6 +44,8 @@ def valid_encoding?(str) # :nodoc: end def coerce_key(key, as_json) # :nodoc: + return key.to_s unless as_json + as_json_called = false unless String === key || Symbol === key @@ -151,11 +153,7 @@ def on_duplicate_key(hash, as_json) }) generator::State.rfc8785_sort_keys_proc = shareable_lambda(->(hash, as_json) { - converted = if as_json - hash.transform_keys { |k| Ext.coerce_key(k, as_json) } - else - hash.transform_keys(&:to_s) - end + converted = hash.transform_keys { |k| Ext.coerce_key(k, as_json) } if converted.size < hash.size Ext.on_duplicate_key(hash, as_json) diff --git a/test/json/json_generator_test.rb b/test/json/json_generator_test.rb index c3087d25..c9367194 100755 --- a/test/json/json_generator_test.rb +++ b/test/json/json_generator_test.rb @@ -1392,6 +1392,13 @@ def test_rfc8785_mixed_key_order assert_rfc8785 '{"a":1,"b":2}', { a: 1, 'b' => 2 } end + def test_rfc8785_duplicate_key_raise_generator_error + hash = { "1" => "user", 1 => "admin" } + assert_raise(JSON::GeneratorError) do + JSON.generate(hash, rfc8785: true) + end + end + def test_rfc8785_key_order_with_as_json key = Object.new def key.to_s