Skip to content

Commit 0e0f0df

Browse files
byroothsbt
authored andcommitted
Fix JSON::Coder to cast non-string keys.
1 parent c3a80ca commit 0e0f0df

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

ext/json/generator/generator.c

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,9 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
10261026
}
10271027

10281028
VALUE key_to_s;
1029+
bool as_json_called = false;
1030+
1031+
start:
10291032
switch (rb_type(key)) {
10301033
case T_STRING:
10311034
if (RB_LIKELY(RBASIC_CLASS(key) == rb_cString)) {
@@ -1039,7 +1042,13 @@ json_object_i(VALUE key, VALUE val, VALUE _arg)
10391042
break;
10401043
default:
10411044
if (data->state->strict) {
1042-
raise_generator_error(key, "%"PRIsVALUE" not allowed in JSON", rb_funcall(key, i_to_s, 0));
1045+
if (RTEST(data->state->as_json) && !as_json_called) {
1046+
key = rb_proc_call_with_block(data->state->as_json, 1, &key, Qnil);
1047+
as_json_called = true;
1048+
goto start;
1049+
} else {
1050+
raise_generator_error(key, "%"PRIsVALUE" not allowed as object key in JSON", CLASS_OF(key));
1051+
}
10431052
}
10441053
key_to_s = rb_convert_type(key, T_STRING, "String", "to_s");
10451054
break;

test/json/json_coder_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ def test_json_coder_with_proc_with_unsupported_value
1818
assert_raise(JSON::GeneratorError) { coder.dump([Object.new]) }
1919
end
2020

21+
def test_json_coder_hash_key
22+
obj = Object.new
23+
coder = JSON::Coder.new(&:to_s)
24+
assert_equal %({#{obj.to_s.inspect}:1}), coder.dump({ obj => 1 })
25+
26+
coder = JSON::Coder.new { 42 }
27+
error = assert_raise JSON::GeneratorError do
28+
coder.dump({ obj => 1 })
29+
end
30+
assert_equal "Integer not allowed as object key in JSON", error.message
31+
end
32+
2133
def test_json_coder_options
2234
coder = JSON::Coder.new(array_nl: "\n") do |object|
2335
42

0 commit comments

Comments
 (0)