Skip to content

encoding/json: add context during decoding when disallowUnknownFields is set #71638

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/encoding/json/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package json
import (
"encoding"
"encoding/base64"
"errors"
"fmt"
"reflect"
"strconv"
Expand Down Expand Up @@ -732,7 +733,11 @@ func (d *decodeState) object(v reflect.Value) error {
d.errorContext.Struct = t
d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name)
} else if d.disallowUnknownFields {
d.saveError(fmt.Errorf("json: unknown field %q", key))
errMsg := fmt.Sprintf("json: unknown field %q", key)
if d.errorContext != nil && len(d.errorContext.FieldStack) > 0 {
errMsg += fmt.Sprintf(" within %q", strings.Join(d.errorContext.FieldStack, "."))
}
d.saveError(errors.New(errMsg))
}
}

Expand Down
18 changes: 17 additions & 1 deletion src/encoding/json/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1031,7 +1031,23 @@ var unmarshalTests = []struct {
Embed0q: Embed0q{Point: Point{Z: 17}},
embed: embed{Q: 18},
},
err: fmt.Errorf("json: unknown field \"extra\""),
err: fmt.Errorf("json: unknown field \"extra\" within \"e\""),
disallowUnknownFields: true,
},
{
CaseName: Name(""),
in: `{"PP": {"T": {"Y": 1, "ZZZ": 1}}}`,
ptr: new(P),
out: P{PP: PP{T: T{Y: 1}}},
err: fmt.Errorf("json: unknown field \"ZZZ\" within \"PP.T\""),
disallowUnknownFields: true,
},
{
CaseName: Name(""),
in: `{"PP": {"Ts": [{"Y": 1, "ZZZ": 1}]}}`,
ptr: new(P),
out: P{PP: PP{Ts: []T{{Y: 1}}}},
err: fmt.Errorf("json: unknown field \"ZZZ\" within \"PP.Ts\""),
disallowUnknownFields: true,
},
// issue 26444
Expand Down