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 <joetsai@google.com>
Run-TryBot: Joe Tsai <joetsai@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Ivan Bertona 2017-10-31 13:16:38 -07:00 committed by Joe Tsai
parent d58f4e9b7b
commit 2596a0c075
3 changed files with 95 additions and 10 deletions

View file

@ -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))
}
}