From 2596a0c075aeddec571cd658f748ac7a712a2b69 Mon Sep 17 00:00:00 2001 From: Ivan Bertona Date: Tue, 31 Oct 2017 13:16:38 -0700 Subject: encoding/json: disallow unknown fields in Decoder Add a DisallowUnknownFields flag to Decoder. DisallowUnknownFields causes the Decoder to return an error when the the decoding destination is a struct and the input contains object keys which do not match any non-ignored, public field the destination, including keys whose value is set to null. Note: this fix has already been worked on in 27231, which seems to be abandoned. This version is a slightly simpler implementation and is up to date with the master branch. Fixes #15314 Change-Id: I987a5857c52018df334f4d1a2360649c44a7175d Reviewed-on: https://go-review.googlesource.com/74830 Reviewed-by: Joe Tsai Run-TryBot: Joe Tsai TryBot-Result: Gobot Gobot --- src/encoding/json/decode.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src/encoding/json/decode.go') diff --git a/src/encoding/json/decode.go b/src/encoding/json/decode.go index 44f9035358..70179e60ac 100644 --- a/src/encoding/json/decode.go +++ b/src/encoding/json/decode.go @@ -44,8 +44,9 @@ import ( // // To unmarshal JSON into a struct, Unmarshal matches incoming object // keys to the keys used by Marshal (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. -// Unmarshal will only set exported fields of the struct. +// preferring an exact match but also accepting a case-insensitive match. By +// default, object keys which don't have a corresponding struct field are +// ignored (see Decoder.DisallowUnknownFields for an alternative). // // To unmarshal JSON into an interface value, // Unmarshal stores one of these in the interface value: @@ -275,8 +276,9 @@ type decodeState struct { Struct string Field string } - savedError error - useNumber bool + savedError error + useNumber bool + disallowUnknownFields bool } // errPhase is used for errors that should not happen unless @@ -713,6 +715,8 @@ func (d *decodeState) object(v reflect.Value) { } d.errorContext.Field = f.name d.errorContext.Struct = v.Type().Name() + } else if d.disallowUnknownFields { + d.saveError(fmt.Errorf("json: unknown field %q", key)) } } -- cgit v1.3