Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion lib/json/ext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down