From c8dc19ec818d288e3393883ee61931a43394f4eb Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Sun, 29 Nov 2026 08:56:14 +0100 Subject: [PATCH] Properly raise `JSON::GeneratorError` for duplicate keys Fix: https://github.com/ruby/json/issues/1152 --- CHANGES.md | 2 ++ lib/json/ext.rb | 8 +++----- test/json/json_generator_test.rb | 7 +++++++ 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 55266e9c6..ccffd169f 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 75d0e4e3d..4de400bc9 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 c3087d25e..c9367194b 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