Selective JSON Decode With RawMessage
Decode only the known fields via map[string]json.RawMessage and pass every other key through untouched, so unfamiliar payloads survive the round trip.
Code
package main
import (
"encoding/json"
"fmt"
)
type Check struct {
Required []string `json:"required"`
Timeout int `json:"timeout"`
}
func main() {
payload := []byte(`{"required":["name"],"timeout":3,"future_mode":"beta","tags":["a","b"]}`)
// 先只看顶层键:未知键保持原始字节,不丢也不报错
var fields map[string]json.RawMessage
if err := json.Unmarshal(payload, &fields); err != nil {
panic(err)
}
var check Check
if raw, ok := fields["required"]; ok {
if err := json.Unmarshal(raw, &check.Required); err != nil {
panic(err)
}
}
if raw, ok := fields["timeout"]; ok {
if err := json.Unmarshal(raw, &check.Timeout); err != nil {
panic(err)
}
}
fmt.Printf("decoded: required=%v timeout=%d\n", check.Required, check.Timeout)
fmt.Println("passthrough keys:", len(fields)-2)
}Decode known fields, keep everything else
The payload is unmarshaled into map[string]json.RawMessage, which splits the JSON into top-level keys while storing each value as untouched raw bytes. Only two keys are decoded in place — fields["required"] into check.Required and fields["timeout"] into check.Timeout, each guarded by the if raw, ok := fields[…]; ok presence check. The unknown keys (future_mode, tags) are never parsed, so unfamiliar fields survive the read without errors or loss.
Counts from one payload
decoded: required=[name] timeout=3
passthrough keys: 2
Line one is the decoded Check (required as the slice ["name"], timeout as 3). The second counts what was left alone: len(fields)-2 where len(fields) is 4 — the two passthrough keys, still carrying their original bytes for downstream code.
The line that defers parsing
var fields map[string]json.RawMessage
if err := json.Unmarshal(payload, &fields); err != nil {
panic(err)
}
Because RawMessage is just []byte, a later feature can decode fields["future_mode"] into whatever type it grows into — the round trip through this map never commits to a schema it does not know.
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 3 checkpoints test `err` and abort the run on the first non-nil one.
- What does Selective JSON Decode With RawMessage print when run?
- Run it as a complete program — the output lines carry labels such as `decoded: required=`, `passthrough keys:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.