JSON RawMessage For Deferred Parsing
Hold nested payloads as json.RawMessage and parse them only when needed, so routing decisions avoid decoding the whole document.
Code
package main
import (
"encoding/json"
"fmt"
)
type Envelope struct {
Kind string `json:"kind"`
Payload json.RawMessage `json:"payload"`
}
type Created struct {
ID string `json:"id"`
}
type Deleted struct {
ID string `json:"id"`
Reason string `json:"reason"`
}
func main() {
raw := []byte(`{"kind":"created","payload":{"id":"e-1"}}`)
var env Envelope
if err := json.Unmarshal(raw, &env); err != nil {
fmt.Println("decode failed:", err)
return
}
fmt.Println("kind:", env.Kind, "| payload bytes:", len(env.Payload))
// 延迟解析:只解需要的分支类型
switch env.Kind {
case "created":
var body Created
if err := json.Unmarshal(env.Payload, &body); err == nil {
fmt.Println("created id:", body.ID)
}
case "deleted":
var body Deleted
if err := json.Unmarshal(env.Payload, &body); err == nil {
fmt.Println("deleted id:", body.ID, "reason:", body.Reason)
}
}
}How the snippet works
Count the function main as the entire surface area of JSON RawMessage For Deferred Parsing.
err is inspected at 1 call site before any result is trusted.
Applying it
The demo output is labeled (decode failed:, kind:, created id:), so every line of output can be traced to the operation that made it.
Statements that matter most here
raw := []byte(`{"kind":"created","payload":{"id":"e-1"}}`)
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does JSON RawMessage For Deferred Parsing print when run?
- Invoke the file as-is — the `decode failed:`, `kind:`, `created id:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.