Strict JSON Decoding Rejects Unknown Fields
Reject JSON payloads with unexpected keys by enabling DisallowUnknownFields, so typos and stale clients surface as decode errors instead of zero values.
Code
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Profile struct {
Handle string `json:"handle"`
Region string `json:"region"`
}
func decode(input string) (Profile, error) {
dec := json.NewDecoder(strings.NewReader(input))
// 严格模式:未知键按错误处理,而不是静默落成零值
dec.DisallowUnknownFields()
var p Profile
if err := dec.Decode(&p); err != nil {
return Profile{}, err
}
return p, nil
}
func main() {
good := `{"handle":"ada","region":"eu"}`
if p, err := decode(good); err == nil {
fmt.Printf("ok: %+v\n", p)
}
// "zone" 不在 Profile 里:解码被拒绝并给出字段名
bad := `{"handle":"bob","zone":"us","region":"ap"}`
if _, err := decode(bad); err != nil {
fmt.Println("rejected:", err)
}
}How the snippet works
Count the functions decode and main as the entire surface area of Strict JSON Decoding Rejects Unknown Fields.
Error handling is inline: 2 places test err != nil and branch immediately.
What to watch for
- There are no exceptions to catch —
errreturn values must be checked at each call site.
Applying it
Entry signature: func decode(input string) (Profile, error)
The demo output is labeled (ok:, rejected:), so each line traces straight back to the statement that printed it.
Execute the file and main walks through decode, in that order.
Statements that decide the outcome
func decode(input string) (Profile, error) {
dec := json.NewDecoder(strings.NewReader(input))
// 严格模式:未知键按错误处理,而不是静默落成零值
dec.DisallowUnknownFields()
var p Profile
if err := dec.Decode(&p); err != nil {
return Profile{}, err
}
return p, nil
}
func main() {
good := `{"handle":"ada","region":"eu"}`
if p, err := decode(good); err == nil {
fmt.Printf("ok: %+v\n", p)
}
// "zone" 不在 Profile 里:解码被拒绝并给出字段名
bad := `{"handle":"bob","zone":"us","region":"ap"}`
if _, err := decode(bad); err != nil {
fmt.Println("rejected:", err)
}
}
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
FAQ
- What happens when a call fails?
- The Go way: `err` comes back from each call, and 2 checkpoints here test it before proceeding.
- What does Strict JSON Decoding Rejects Unknown Fields print when run?
- Invoke the file as-is — the `ok:`, `rejected:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.