How to Use json.RawMessage for Deferred Decoding

Use json.RawMessage to store JSON as raw bytes and defer parsing until the data is explicitly accessed.

Use json.RawMessage to store JSON as a raw byte slice, deferring parsing until you explicitly need the data. This prevents the encoding/json package from unmarshaling the field immediately, saving CPU and memory if the field is never accessed.

import "encoding/json"

type Config struct {
    Name string          `json:"name"`
    Data json.RawMessage `json:"data"` // Deferred decoding
}

func main() {
    var c Config
    json.Unmarshal([]byte(`{"name":"test","data":{"key":"value"}}`), &c)

    // Parse 'Data' only when needed
    var details map[string]interface{}
    json.Unmarshal(c.Data, &details)
}