Support non string map keys (#756)

* fix map keys misencoding to string

* Add unit tests

* Add tests for decoder with unconventional map keys

---------

Co-authored-by: Zsolt Herczeg <herczegzsolt@herczegzsolt.hu>
This commit is contained in:
Shuhei Kitagawa 2025-11-29 03:37:53 +01:00 committed by GitHub
parent f4d13479ba
commit 7901e98f54
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 45 additions and 1 deletions

View file

@ -494,6 +494,24 @@ func TestDecoder(t *testing.T) {
value: map[string]interface{}{"a": "50cent_of_dollar"},
},
// Unconventional keys
{
source: "1: v\n",
value: map[int]string{1: "v"},
},
{
source: "1.1: v\n",
value: map[float64]string{1.1: "v"},
},
{
source: "true: v\n",
value: map[bool]string{true: "v"},
},
{
source: "2015-01-01T00:00:00Z: v\n",
value: map[time.Time]string{time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC): "v"},
},
// Nulls
{
source: "null",

View file

@ -712,9 +712,15 @@ func (e *Encoder) encodeMap(ctx context.Context, value reflect.Value, column int
anchorNode.Value = encoded
encoded = anchorNode
}
kn, err := e.encodeValue(ctx, reflect.ValueOf(key), column)
keyNode, ok := kn.(ast.MapKeyNode)
if !ok || err != nil {
keyNode = e.encodeString(fmt.Sprint(key), column)
}
node.Values = append(node.Values, ast.MappingValue(
nil,
e.encodeString(keyText, column),
keyNode,
encoded,
))
e.setSmartAnchor(vRef, keyText)

View file

@ -187,6 +187,26 @@ func TestEncoder(t *testing.T) {
map[string]string{"a": "-"},
nil,
},
{
"1: v\n",
map[int]string{1: "v"},
nil,
},
{
"1.1: v\n",
map[float64]string{1.1: "v"},
nil,
},
{
"true: v\n",
map[bool]string{true: "v"},
nil,
},
{
"2015-01-01T00:00:00Z: v\n",
map[time.Time]string{time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC): "v"},
nil,
},
{
"123\n",
123,