Go Reference ยท Encoding and Data Formats
Go json.RawMessage type
Reference for Go json.RawMessage: keep part of a JSON document undecoded, pick a type from a discriminator field, embed pre-encoded JSON and avoid double work.
json.RawMessage is a []byte that implements both json.Marshaler and json.Unmarshaler. As a struct field, it captures the JSON text of that field exactly as it appeared, without decoding it. When encoding, it writes its bytes straight into the output as JSON.
That gives you two tricks: delay decoding until you know which Go type to use (a "type" field tells you what the "payload" holds), and pass JSON through a program untouched.
type Envelope struct { Kind string `json:"kind"` Payload json.RawMessage `json:"payload"` }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type RawMessage []byte func (m RawMessage) MarshalJSON() ([]byte, error) func (m *RawMessage) UnmarshalJSON(data []byte) error
| Behavior | Description |
|---|---|
| Decoding | UnmarshalJSON appends the field's JSON text to the slice, including any whitespace inside the value but not around it. A JSON null leaves the text null. |
| Encoding | A non-nil value is written as-is after validation and compaction; a nil value writes null. |
Errors. Marshaling a RawMessage that is not valid JSON returns a *json.MarshalerError. UnmarshalJSON on a nil pointer receiver returns an error.
Usage notes
- Use a value receiver trick:
MarshalJSONhas a value receiver (since Go 1.8), so aRawMessagefield encodes correctly even when the struct is passed by value. Old code with*json.RawMessagefields is no longer required. - The bytes are a copy.
UnmarshalJSONcopies the field's text, so the message stays valid after the input buffer is reused. Decoding again into the sameRawMessageoverwrites its previous contents. - Two-pass decoding costs time. The payload is scanned once for validity and again when you decode it. This is usually fine and beats decoding into
map[string]any. - Preserving exact text: a raw message keeps big numbers (
12345678901234567890) and key order intact, whichanywould not. - Alternatives: for fully custom logic, implement
UnmarshalJSONon your own type. For numbers only, usejson.Number. - Not a string: printing a
RawMessagewith%sshows JSON text; with%vshows a byte slice of numbers. - Security: treat the content as untrusted until decoded into a concrete, validated type.