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.

GoData Fetching

Code

gosnippet
45 lines
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

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.