Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] JSON.dump for hash with duplicate key #564

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 19 additions & 2 deletions lib/json/common.rb
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,8 @@ def dump(obj, anIO = nil, limit = nil, kwargs = nil)
opts = JSON.dump_default_options
opts = opts.merge(:max_nesting => limit) if limit
opts = merge_dump_options(opts, **kwargs) if kwargs
result = generate(obj, opts)
sanitized_obj = make_json_compatible(obj)
result = generate(sanitized_obj, opts)
if anIO
anIO.write result
anIO
Expand All @@ -644,8 +645,24 @@ def merge_dump_options(opts, strict: NOT_SET)
opts
end

def make_json_compatible(obj)
case obj
when Hash
result = {}
obj.each do |k, v|
k = k.to_s unless String === k
result[k] = make_json_compatible(v)
end
result
when Array
obj.map { |v| make_json_compatible(v) }
else
obj
end
end

class << self
private :merge_dump_options
private :merge_dump_options, :make_json_compatible
end
end

Expand Down
4 changes: 4 additions & 0 deletions tests/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ def test_dump_strict
assert_equal '{}', dump({}, strict: true)
end

def test_dump_duplicate_key_hash
assert_equal "{\"a\":5,\"c\":{\"b\":6}}", dump({ 'a' => 1, a: 5, c: { 'b' => 2, b: 6 } })
end

def test_generate_pretty
json = pretty_generate({})
assert_equal(<<'EOT'.chomp, json)
Expand Down