Skip to content
Merged
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

* 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
Expand Down
8 changes: 3 additions & 5 deletions lib/json/ext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading