Strict JSON Decode With DisallowUnknownFields

Decode config JSON with DisallowUnknownFields so a typoed or renamed key fails loudly at startup instead of being ignored and leaving zero values behind.

GoConfig Management

Code

gosnippet
35 lines
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func main() {
	// The config sneaks in an unknown debug field: a default Decode silently ignores it
	payload := `{"host":"db.internal","port":5432,"debug":true}`

	var cfg struct {
		Host string `json:"host"`
		Port int    `json:"port"`
	}

	dec := json.NewDecoder(strings.NewReader(payload))
	dec.DisallowUnknownFields() // unknown keys now error out directly
	if err := dec.Decode(&cfg); err != nil {
		fmt.Println("strict decode:", err)
	}

	// Without the extra field: strict mode passes and the fields actually land in the struct
	clean := `{"host":"db.internal","port":5432}`
	var good struct {
		Host string `json:"host"`
		Port int    `json:"port"`
	}
	dec = json.NewDecoder(strings.NewReader(clean))
	if err := dec.Decode(&good); err != nil {
		panic(err)
	}
	fmt.Printf("%s:%d\n", good.Host, good.Port)
}

How it works

Everything happens inside the function main.

Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

What to watch for

  • Runs on the standard library alone; nothing to install.
  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Using it

The signature you will reach for first is func main()

The demo output is labeled (strict decode:), so each printed line points back to the operation that produced it.

Key statements

dec.DisallowUnknownFields() // unknown keys now error out directly

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 2 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does Strict JSON Decode With DisallowUnknownFields print when run?
Running the file directly is enough — expect labeled output lines such as `strict decode:`.