Skip to content

Commit 37213aa

Browse files
committed
encoding/json: fix UnmarshalTypeError without field & struct values
Fixes golang#26444
1 parent 1a5350e commit 37213aa

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/encoding/json/decode.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,7 @@ func (d *decodeState) object(v reflect.Value) error {
672672
}
673673

674674
var mapElem reflect.Value
675+
originalErrorContext := d.errorContext
675676

676677
for {
677678
// Read opening " of string key or closing }.
@@ -832,8 +833,7 @@ func (d *decodeState) object(v reflect.Value) error {
832833
return errPhase
833834
}
834835

835-
d.errorContext.Struct = ""
836-
d.errorContext.Field = ""
836+
d.errorContext = originalErrorContext
837837
}
838838
return nil
839839
}
@@ -991,7 +991,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool
991991
if fromQuoted {
992992
return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
993993
}
994-
return &UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())}
994+
return d.addErrorContext(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
995995
case reflect.Interface:
996996
n, err := d.convertNumber(s)
997997
if err != nil {

src/encoding/json/decode_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,10 @@ func (b *intWithPtrMarshalText) UnmarshalText(data []byte) error {
371371
return (*intWithMarshalText)(b).UnmarshalText(data)
372372
}
373373

374+
type mapStringToStringData struct {
375+
Data map[string]string `json:"data"`
376+
}
377+
374378
type unmarshalTest struct {
375379
in string
376380
ptr interface{}
@@ -866,6 +870,18 @@ var unmarshalTests = []unmarshalTest{
866870
err: fmt.Errorf("json: unknown field \"extra\""),
867871
disallowUnknownFields: true,
868872
},
873+
// issue 26444
874+
// UnmarshalTypeError without field & struct values
875+
{
876+
in: `{"data":{"test1": "bob", "test2": 123}}`,
877+
ptr: new(mapStringToStringData),
878+
err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 37, Struct: "mapStringToStringData", Field: "data"},
879+
},
880+
{
881+
in: `{"data":{"test1": 123, "test2": "bob"}}`,
882+
ptr: new(mapStringToStringData),
883+
err: &UnmarshalTypeError{Value: "number", Type: reflect.TypeOf(""), Offset: 21, Struct: "mapStringToStringData", Field: "data"},
884+
},
869885
}
870886

871887
func TestMarshal(t *testing.T) {

0 commit comments

Comments
 (0)