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.
Code
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
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.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.