1. Why do we need "strictness" when parsing JSON at all
When you are just starting to write programs, you really want the computer to be kind and forgive mistakes. But with data it is the other way around: the "kinder" the parser, the greater the chance that it will quietly swallow a problem — and you will end up with a bug that appears three weeks later, on Friday evening, and for some reason only on a colleague's machine.
By default, encoding/json in Go is quite tolerant: it tries to fill in what it can and does not throw a fit over extra fields. That is convenient for format compatibility, but dangerous when you expect a strictly fixed contract. In this lecture, we will learn how to turn on "picky mode": "if I do not know the field, then it is an error."
How encoding/json matches struct fields and JSON fields
Before turning on strict mode, it is important to understand what exactly counts as "known" and "unknown". encoding/json works in a very down-to-earth way: it sees a JSON object {...}, looks at the keys, and tries to find a matching field in the struct. If the field is exported (starts with a capital letter) and matches by name/tag, it writes the value.
For example, here is a small DTO (a structure into which we read JSON). For now, let's make a simple "task" model for our training application (a hypothetical todo/task-tracker), so that the examples stay connected across the lectures:
package main
type TaskDTO struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
Important point: json:"title" is a contract. If the JSON contains the key "title", it will go into Title. If it contains "Title" or "taskTitle", that is a different story altogether (and often the source of surprises).
2. The problem of "extra fields": when there is an error, but nobody noticed
Now we come to the main pain point. Imagine: the user (or your own code, but a week ago) sends JSON with a typo in one place: "titel" instead of "title". A person expects the program to say, "hey, that field is wrong." But by default the program often pretends everything is fine: it simply ignores the unknown key, and Title stays an empty string.
Here is a demonstration of the "silent" behavior (intentionally without strict mode):
package main
import (
"encoding/json"
"fmt"
)
func main() {
data := []byte(`{"id": 1, "titel": "Buy milk", "done": false}`)
var t TaskDTO
_ = json.Unmarshal(data, &t)
fmt.Printf("%+v\n", t) // {ID:1 Title: Done:false}
}
Here everything is "successful", but the task suddenly has no title. And then you can spend hours debugging "why Title is empty", although the root cause is a typo in the input data.
This behavior is not unique to JSON in general: the idea of "fill only matching fields, ignore the rest" appears in other codecs as well. For example, gob format descriptions emphasize matching fields by name and the fact that fields that "have nowhere to go" are ignored.
4. Decoder.DisallowUnknownFields(): turn on strict mode
To stop "forgiving" extra fields when reading into a struct, Go gives us a very direct setting: Decoder.DisallowUnknownFields(). It is enabled not globally for the package, but on a specific decoder, that is, right where you read the input.
The pattern is this: create json.NewDecoder(r), enable strict mode, call Decode(&v).
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
r := strings.NewReader(`{"id": 1, "titel": "Buy milk", "done": false}`)
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
var t TaskDTO
err := dec.Decode(&t)
fmt.Println(err) // json: unknown field "titel"
}
And this already feels like adult life: we did not get an "empty Title", we got a clear error. Yes, it is unpleasant for the user who made the mistake, but it is honest. And most importantly, it saves you time.
A couple of subtle points are worth saying out loud so that there is no "magic".
First, strict mode applies specifically to decoding into a struct. If you decode into a map[string]any, then there are no "unknown fields" — the map is ready to accept any keys.
Second, strict mode helps catch typos and unexpected data, but it does not replace validation of required fields. If the "title" field is missing, strict mode will not complain — it will simply leave Title at the zero value (an empty string), and then your validation must say "title is required".
5. Why strict mode does not always work
After enabling DisallowUnknownFields, it is tempting to believe that now "everything is safe" and JSON cannot fool us. But it is important to understand the boundaries.
If you do this:
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
r := strings.NewReader(`{"id": 1, "titel": "Buy milk", "done": false}`)
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
var m map[string]any
err := dec.Decode(&m)
fmt.Println(err) // <nil>
fmt.Println(m["titel"]) // Buy milk
}
There is no error — because we did not ask the decoder to match keys against struct fields. For a map, every field is "known".
This is not a bug, just a different purpose: map[string]any is used when the format is truly dynamic or when you are writing a universal "proxy"/"middleware" layer. But if you have a fixed input contract, it is better to read into a struct — and then strict mode starts working as intended.
6. One more level of strictness: one JSON and no trailing data
Strictness is not only about "unknown fields". There is another classic problem: the input contains not one JSON document, but two in a row, or JSON plus some garbage "tail". For example:
{"id":1,"title":"Buy milk","done":false} hey there
or even this:
{"id":1,"title":"Buy milk","done":false}
{"id":2,"title":"Pay bills","done":true}
Decode reads one JSON value per call. And if you made one Decode, it is not obligated to automatically check that the stream ended after that. That is why in a "strict contract" people often use this trick: after the first Decode, call Decode again and make sure that it returns io.EOF.
Let's make a small reusable helper, decodeOneStrict. It does two strict checks at once: it forbids unknown fields and it forbids "extra data" after the JSON.
package main
import (
"encoding/json"
"fmt"
"io"
)
func decodeOneStrict(r io.Reader, v any) error {
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
return err
}
// Check that there is no second JSON value after this.
if err := dec.Decode(&struct{}{}); err != io.EOF {
if err == nil {
return fmt.Errorf("unexpected extra JSON value")
}
return fmt.Errorf("trailing data: %w", err)
}
return nil
}
Notice: we decode "into nowhere" using &struct{}{}. We do not care about the value, we care about the decoder's behavior. If there is a second JSON value, the second Decode will return nil. If there is garbage that does not start like JSON, the error will not be io.EOF. If everything is clean, it will be io.EOF.
7. Integrating strict parsing into the application
To keep the topic from feeling too abstract, let's embed it into the logic of our training "task tracker" application. Still without CLI flags and without HTTP: we will simply read one task from an io.Reader. This will be useful later both for reading from a file and from stdin, and for tests using strings.NewReader.
Let's make a function ReadTaskStrict that reads one task strictly and returns the structure.
package main
import (
"fmt"
"io"
)
func ReadTaskStrict(r io.Reader) (TaskDTO, error) {
var t TaskDTO
if err := decodeOneStrict(r, &t); err != nil {
return TaskDTO{}, fmt.Errorf("read task: %w", err)
}
return t, nil
}
Here we added context to the error via fmt.Errorf("...": %w, err). That is a good habit: when the error bubbles up, you will understand at which step it occurred.
By the way, encoding/json has typed errors (for example, *json.SyntaxError contains the offset Offset), and the idea that "an error is a value that can contain useful fields" is actively used in Go. This becomes especially nice when you start doing diagnostics like "syntax error at byte N".
Let's check what this looks like in a mini-main:
package main
import (
"fmt"
"strings"
)
func main() {
input := `{"id": 1, "titel": "Buy milk", "done": false}`
t, err := ReadTaskStrict(strings.NewReader(input))
fmt.Println(t) // {0 false}
fmt.Println(err) // read task: json: unknown field "titel"
}
The error is visible, and the context "read task" is visible too. For the user (or for your future self) that is much better than a silent zero.
8. Useful nuances of strict decoding
Table: levels of strictness in decoding
When you design input, it is useful to decide in advance whether you want to be "strict" or "friendly to the future". Sometimes a format must be extensible, and then extra fields are better ignored. And sometimes you are processing commands/configs where a typo is a critical error. At this point it is useful to keep in mind what "strictness knobs" we actually have.
| Approach | What we catch | What we do not catch | Where it makes sense |
|---|---|---|---|
| Plain Decode/Unmarshal | Bad JSON syntax, type mismatches | Typos in field names, second JSON value in the stream | Flexible/evolving format, compatibility |
| DisallowUnknownFields() | Unknown fields when decoding into a struct | "Trailing data" after JSON, second JSON document | Fixed contract (config, API request) |
| DisallowUnknownFields + io.EOF check | Both unknown fields and trailing data/second JSON | Missing required fields (validation needed) | Strict input, import, critical operations |
Where exactly strict checking should live
To avoid mixing up application "layers", it is useful to draw a simple diagram. Strict parsing is part of the decode stage, not the business logic. Business logic should receive already valid structures and think about meaning, not syntax.
flowchart TD
A[io.Reader: file / stdin / string] --> B[json.Decoder + DisallowUnknownFields]
B --> C["Decode(&dto) + check EOF"]
C --> D[Post-validation of fields]
D --> E[Business logic: create/update task]
This diagram is good because it shows that strict mode does not replace validation — it complements it. First we guarantee the "structure contract", then we guarantee the "meaning contract".
9. Typical mistakes in strict JSON parsing
Mistake #1: we enabled DisallowUnknownFields, but decode into map[string]any, and expect it to work.
This is a common trap because on the surface it seems: "but I did turn on strict mode". Yet unknown fields are a notion only relative to a struct. If the receiver is a map, then all fields are "known", and there is nothing to check. If the contract is fixed, decode into a struct.
Mistake #2: people check unknown fields, but forget to check for "extra data" after the JSON.
In the streaming model, Decode reads one value. If the input contains two JSON values in a row, the first Decode will succeed, and you get a "half-truth": the first object was read, and the fact that there was garbage after it was ignored. The fix is the pattern "the second Decode must return io.EOF".
Mistake #3: confusing zero value with field absence.
Even in strict mode, missing the "done" field is not an error: Done will simply be false. Likewise, missing "title" leaves an empty string. If a field must be required, that is solved by post-validation, not by DisallowUnknownFields.
Mistake #4: returning a "bare" error without context and then not understanding where it came from.
When your program has several places that read JSON (config, import, network input), an error like json: unknown field "titel" without context makes you guess: "where is this from?" The habit of adding context via fmt.Errorf("decode task: %w", err) makes life much easier. And the very idea that "an error can store details (for example, an offset in JSON)" is part of Go's approach to errors.
GO TO FULL VERSION