JSON RawMessage Deferred Decoding
Defer payload decoding with json.RawMessage: keep raw bytes in the envelope struct, then decode into the right target type once the kind is known.
Code
package main
import (
"encoding/json"
"fmt"
)
type Envelope struct {
Kind string `json:"kind"`
Payload json.RawMessage `json:"payload"` // 先收下原始字节,稍后解码
}
type Click struct {
URL string `json:"url"`
Hits int `json:"hits"`
}
func main() {
in := `{"kind":"click","payload":{"url":"/pricing","hits":3}}`
var env Envelope
if err := json.Unmarshal([]byte(in), &env); err != nil {
fmt.Println("decode error:", err)
return
}
fmt.Println("kind:", env.Kind)
// 按消息类型选择目标结构:解码错误推迟到真正解 payload 时
switch env.Kind {
case "click":
var click Click
if err := json.Unmarshal(env.Payload, &click); err != nil {
fmt.Println("payload error:", err)
return
}
fmt.Printf("payload: %+v\n", click)
default:
fmt.Println("unknown kind, payload kept raw:", string(env.Payload))
}
// RawMessage 原样透传:重新封包不丢字段、不改格式
out, _ := json.Marshal(map[string]any{"kind": env.Kind, "payload": env.Payload})
fmt.Println("re-encoded:", string(out))
}How it works
JSON RawMessage Deferred Decoding keeps everything in the function main.
Error handling is inline: 2 places test err != nil and branch immediately.
Putting it to use
Each run prints the 6 labeled blocks decode error:, kind:, payload error:, payload:, unknown kind, payload kept raw:, re-encoded: in source order.
The core lines of the flow
out, _ := json.Marshal(map[string]any{"kind": env.Kind, "payload": env.Payload})
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 Deferred Decoding print when run?
- The script runs standalone; its 6 labeled outputs include `decode error:`, `kind:`, `payload error:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.