From f3b0be31407611e43ee119139f0dd44b1071735a Mon Sep 17 00:00:00 2001 From: branson404 <78994175+branson404@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:48:13 +0000 Subject: [PATCH] Raise GeneratorError for colliding keys with rfc8785 and no as_json In rfc8785 mode the duplicate key check re-coerced every key through as_json, which is nil for a non-strict generator and false for a strict Coder without a block, so a hash such as { "1" => 1, 1 => 2 } raised NoMethodError. Without an as_json converter the keys are stringified, as the sort proc already does, so do the same when looking for the duplicate. Fixes #1152. --- CHANGES.md | 2 ++ lib/json/ext.rb | 3 ++- test/json/json_generator_test.rb | 9 +++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/CHANGES.md b/CHANGES.md index 55266e9c6..207054bde 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -2,6 +2,8 @@ ### Unreleased +* Fix `JSON.generate(hash, rfc8785: true)` raising `NoMethodError` instead of `JSON::GeneratorError` for a hash with colliding keys such as `{ "1" => 1, 1 => 2 }`. + ### 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..7709c812c 100644 --- a/lib/json/ext.rb +++ b/lib/json/ext.rb @@ -80,7 +80,8 @@ def coerce_key(key, as_json) # :nodoc: def on_duplicate_key(hash, as_json) set = {} hash.each_key do |key| - key = coerce_key(key, as_json) + # Without an `as_json` converter keys are stringified, as the caller does when sorting. + key = as_json ? coerce_key(key, as_json) : key.to_s if set[key] raise GeneratorError.new("detected duplicate key #{key.inspect}", key) else diff --git a/test/json/json_generator_test.rb b/test/json/json_generator_test.rb index c3087d25e..e1b1982bc 100755 --- a/test/json/json_generator_test.rb +++ b/test/json/json_generator_test.rb @@ -1392,6 +1392,15 @@ def test_rfc8785_mixed_key_order assert_rfc8785 '{"a":1,"b":2}', { a: 1, 'b' => 2 } end + def test_rfc8785_colliding_keys_raise_generator_error + hash = { '1' => 1, 1 => 2 } + error = assert_raise(JSON::GeneratorError) { JSON.generate(hash, rfc8785: true) } + assert_equal %(detected duplicate key "1"), error.message[/\Adetected duplicate key "1"/] + + assert_raise(JSON::GeneratorError) { JSON.generate({ :'1' => 1, 1 => 2 }, rfc8785: true) } + assert_raise(JSON::GeneratorError) { JSON::Coder.new(rfc8785: true).dump(hash) } + end + def test_rfc8785_key_order_with_as_json key = Object.new def key.to_s