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.

GoData Integrity

Code

gosnippet
36 lines
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 — err return 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

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.