JSON Map Keys With TextMarshaler

Encode integer-keyed maps as readable JSON keys by implementing encoding.TextMarshaler and TextUnmarshaler on a custom key type.

GoData Integrity

Code

gosnippet
47 lines
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 err before 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

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:`.