aboutsummaryrefslogtreecommitdiff
path: root/src/encoding/json/decode.go
diff options
context:
space:
mode:
authorIvan Bertona <ivan.bertona@gmail.com>2017-10-31 13:16:38 -0700
committerJoe Tsai <thebrokentoaster@gmail.com>2017-10-31 22:28:36 +0000
commit2596a0c075aeddec571cd658f748ac7a712a2b69 (patch)
tree7703794a12c402a11fc067d3ca527d96bac658bb /src/encoding/json/decode.go
parentd58f4e9b7b503ed83641e2cd632a19011da6b50c (diff)
downloadgo-2596a0c075aeddec571cd658f748ac7a712a2b69.tar.xz
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>
Diffstat (limited to 'src/encoding/json/decode.go')
-rw-r--r--src/encoding/json/decode.go12
1 files changed, 8 insertions, 4 deletions
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))
}
}