Skip to content

Commit 0ace442

Browse files
committed
encoding/json: fix panic for nil instances of TextMarshaler in map keys
This change adds a a check in the encodeWithString.resolve method to ensure that a reflect.Value with kind Ptr is not nil before the type assertion to TextMarshaler. If the value is nil, the method returns a nil error, and the map key encodes to an empty string. Fixes #33675
1 parent c485506 commit 0ace442

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/encoding/json/encode.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -872,6 +872,9 @@ func (w *reflectWithString) resolve() error {
872872
return nil
873873
}
874874
if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
875+
if w.v.Kind() == reflect.Ptr && w.v.IsNil() {
876+
return nil
877+
}
875878
buf, err := tm.MarshalText()
876879
w.s = string(buf)
877880
return err

src/encoding/json/encode_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,20 @@ func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
793793
}
794794
}
795795

796+
func TestIssue33675(t *testing.T) {
797+
b, err := Marshal(map[*unmarshalerText]int{
798+
(*unmarshalerText)(nil): 1,
799+
&unmarshalerText{"A", "B"}: 2,
800+
})
801+
if err != nil {
802+
t.Fatalf("Failed to Marshal *text.Marshaler: %v", err)
803+
}
804+
const want = `{"":1,"A:B":2}`
805+
if string(b) != want {
806+
t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want)
807+
}
808+
}
809+
796810
var re = regexp.MustCompile
797811

798812
// syntactic checks on form of marshaled floating point numbers.

0 commit comments

Comments
 (0)