JSON Map Keys With TextMarshaler
Encode integer-keyed maps as readable JSON keys by implementing encoding.TextMarshaler and TextUnmarshaler on a custom key type.
Code
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
type AccountID int
// encoding.TextMarshaler supplies JSON object keys, which must encode as strings
func (id AccountID) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("acct-%04d", int(id))), nil
}
func (id *AccountID) UnmarshalText(text []byte) error {
raw, ok := strings.CutPrefix(string(text), "acct-")
if !ok {
return fmt.Errorf("account key %q lacks acct- prefix", text)
}
value, err := strconv.Atoi(raw)
if err != nil {
return fmt.Errorf("account key %q: %w", text, err)
}
*id = AccountID(value)
return nil
}
func main() {
balances := map[AccountID]int{7: 120, 42: 30, 315: 8}
encoded, err := json.Marshal(balances)
if err != nil {
fmt.Println("encode failed:", err)
return
}
fmt.Println(string(encoded)) // 键由 MarshalText 决定
var decoded map[AccountID]int
if err := json.Unmarshal(encoded, &decoded); err != nil {
fmt.Println("decode failed:", err)
return
}
fmt.Println("account 7:", decoded[7])
fmt.Println("account 315:", decoded[315])
}What the file does
What another module actually calls is the functions MarshalText, UnmarshalText and main — everything else is wiring.
Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly.
Caveats
- Handle
errbefore the other return values; that ordering is the whole contract.
Applying it
Entry signature: func (id AccountID) MarshalText() ([]byte, error)
The demo output is labeled (encode failed:, decode failed:, account 7:), so every line in the printed output names the step that produced it.
Statements that matter
return fmt.Errorf("account key %q: %w", text, err)
return fmt.Errorf("account key %q lacks acct- prefix", text)
return []byte(fmt.Sprintf("acct-%04d", int(id))), nil
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- Is there exception handling?
- Through `error` values, not panics — the snippet checks `err != nil` at 3 sites.
- What does JSON Map Keys With TextMarshaler print when run?
- Running the file directly is enough — expect labeled output lines such as `encode failed:`, `decode failed:`, `account 7:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.