Skip to content

Commit 85f3ca7

Browse files
wI2Lmvdan
authored andcommitted
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 Change-Id: I0a04cf690ae67006f6a9c5f8cbb4cc99d236bca8 GitHub-Last-Rev: 6c987c9 GitHub-Pull-Request: #33700 Reviewed-on: https://go-review.googlesource.com/c/go/+/190697 Run-TryBot: Daniel Martí <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Daniel Martí <[email protected]>
1 parent a806c21 commit 85f3ca7

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/encoding/json/encode.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,9 @@ func (w *reflectWithString) resolve() error {
932932
return nil
933933
}
934934
if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
935+
if w.v.Kind() == reflect.Ptr && w.v.IsNil() {
936+
return nil
937+
}
935938
buf, err := tm.MarshalText()
936939
w.s = string(buf)
937940
return err

src/encoding/json/encode_test.go

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

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

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

0 commit comments

Comments
 (0)