Skip to content

Commit 62cc87b

Browse files
committed
Call to_s for keys
1 parent db0378f commit 62cc87b

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

ext/rapidjson/encoder.hh

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,16 @@ class RubyObjectEncoder {
2525
switch(rb_type(key)) {
2626
case T_SYMBOL:
2727
key = rb_sym2str(key);
28-
/* FALLTHRU */
28+
/* FALLTHRU */
2929
case T_STRING:
3030
writer.Key(RSTRING_PTR(key), RSTRING_LEN(key), false);
3131
return;
3232
default:
33-
raise_unknown(key);
33+
{
34+
VALUE str = rb_funcall(key, id_to_s, 0);
35+
Check_Type(str, T_STRING);
36+
encode_string(str);
37+
}
3438
}
3539
}
3640

@@ -133,11 +137,6 @@ class RubyObjectEncoder {
133137
}
134138
}
135139

136-
void raise_unknown(VALUE obj) {
137-
VALUE inspect = rb_inspect(obj);
138-
rb_raise(rb_eEncodeError, "can't encode type: %s", StringValueCStr(inspect));
139-
}
140-
141140
public:
142141
RubyObjectEncoder(): buf(), writer(buf), depth(0) {
143142
};

test/test_encoder.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ def test_encode_hash
5959
assert_equal '{"foo":"bar"}', encode({ "foo" => "bar" })
6060
end
6161

62+
def test_encode_hash_nonstring_keys
63+
assert_equal '{"1":2}', encode({1 => 2})
64+
assert_equal '{"{1=>2}":3}', encode({{1 => 2} => 3})
65+
assert_equal '{"[\\"foo\\"]":"bar"}', encode({["foo"] => "bar"})
66+
assert_match(/{"#<Object:0x[0-9a-f]+>":2}/, encode({Object.new => 2}))
67+
end
68+
6269
def test_encode_string
6370
assert_equal '""', encode("")
6471
assert_equal '"1"', encode("1")

0 commit comments

Comments
 (0)