Decoder Rejects Trailing JSON Data
json.Unmarshal silently ignores bytes after the first JSON value; pair json.Decoder with a second Decode to reject inputs that carry trailing data.
Code
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
)
type Event struct {
Type string `json:"type"`
At int64 `json:"at"`
}
func strictDecode(data []byte) (Event, error) {
dec := json.NewDecoder(bytes.NewReader(data))
var e Event
if err := dec.Decode(&e); err != nil {
return Event{}, err
}
// 尾巴检测:第二次 Decode 必须恰好命中 io.EOF
var extra any
if err := dec.Decode(&extra); err != io.EOF {
if err == nil {
return Event{}, errors.New("trailing data after JSON value")
}
return Event{}, err
}
return e, nil
}
func main() {
good := []byte(`{"type":"login","at":1731628800}`)
tail := []byte(`{"type":"login","at":1731628800} {"type":"evil"}`)
trunc := []byte(`{"type":"login"`)
for _, c := range []struct {
name string
input []byte
}{
{"good", good},
{"with tail", tail},
{"truncated", trunc},
} {
e, err := strictDecode(c.input)
if err != nil {
fmt.Printf("%-10s rejected: %v\n", c.name, err)
continue
}
fmt.Printf("%-10s ok: %+v\n", c.name, e)
}
// 对照:Unmarshal 对尾巴视而不见,照样成功
var ignored Event
fmt.Println("unmarshal with tail:", json.Unmarshal(tail, &ignored) == nil)
}The execution story
Another angle: the work concentrates in the functions strictDecode and main, doing all the work.
Repetition is confined to for _, c := range []struct — the rest of the file is straight-line. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
What to watch for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
Entry signature: func strictDecode(data []byte) (Event, error)
The demo output is labeled (unmarshal with tail:); each label names the call that printed it.
Treat main as the orchestrator calling strictDecode in a fixed order.
Statements that matter
return Event{}, errors.New("trailing data after JSON value")
if err != nil {
fmt.Printf("%-10s rejected: %v\n", c.name, err)
continue
}
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- By return value: each fallible call hands back an `error`, checked at 2 places here.
- What does Decoder Rejects Trailing JSON Data print when run?
- Invoke the file as-is — the `unmarshal with tail:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.