Go

json.RawMessage — Deferred Decoding

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`json.RawMessage` is a `[]byte` that survives a decode pass. Use it for envelope-style JSON where one field's type depends on another (e.g. `{"type":"X","payload":{...}}`).
Go
Raw
package main

import (
    "encoding/json"
    "fmt"
)

type Envelope struct {
    Type    string          `json:"type"`
    Payload json.RawMessage `json:"payload"`     // hold bytes, decode later
}

type SignupPayload { /* ... */ }
type SignupData    struct{ UserID int `json:"user_id"` }
type LoginData     struct{ Email  string `json:"email"` }

func main() {
    raw := []byte(`{"type":"signup","payload":{"user_id":42}}`)

    var env Envelope
    json.Unmarshal(raw, &env)

    switch env.Type {
    case "signup":
        var d SignupData
        json.Unmarshal(env.Payload, &d)
        fmt.Printf("signup: user_id=%d\n", d.UserID)
    case "login":
        var d LoginData
        json.Unmarshal(env.Payload, &d)
        fmt.Printf("login: email=%s\n", d.Email)
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.