Alias Trick Extends UnmarshalJSON
Extend json decoding without recursion: an alias type keeps the default decode while UnmarshalJSON normalizes fields on the way in.
Code
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Config 在解码期做归一化:retries 既接受 3 也接受 "3"
type Config struct {
Retries int `json:"retries"`
Mode string `json:"mode"`
}
// UnmarshalJSON 直接 Unmarshal 进自己会无限递归
func (c *Config) UnmarshalJSON(data []byte) error {
// alias 类型没有方法:先按默认规则解码
type configAlias Config
var raw struct {
configAlias
Retries json.RawMessage `json:"retries"` // 覆盖提升字段,留住原始字节
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
var n int
if err := json.Unmarshal(raw.Retries, &n); err == nil {
raw.configAlias.Retries = n
} else {
var s string
if err := json.Unmarshal(raw.Retries, &s); err != nil {
return fmt.Errorf("retries: want int or string, got %s", raw.Retries)
}
parsed, err := strconv.Atoi(s)
if err != nil {
return fmt.Errorf("retries %q: not a number", s)
}
raw.configAlias.Retries = parsed
}
*c = Config(raw.configAlias)
return nil
}
func main() {
for _, payload := range []string{
`{"retries": 3, "mode": "fast"}`,
`{"retries": "5", "mode": "safe"}`,
`{"retries": "abc", "mode": "safe"}`,
} {
var cfg Config
if err := json.Unmarshal([]byte(payload), &cfg); err != nil {
fmt.Println("rejected:", err)
continue
}
fmt.Printf("ok: retries=%d mode=%s\n", cfg.Retries, cfg.Mode)
}
}The structure at work
Alias Trick Extends UnmarshalJSON is built around the functions UnmarshalJSON and main.
The cycling part of this snippet is for _, payload := range []string. Every fallible call checks err != nil (4 sites), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- The function reports failure by returning
error— callers branch on it before touching other results.
Applying it
Entry signature: func (c *Config) UnmarshalJSON(data []byte) error
Output lines are prefixed (rejected:, ok: retries=), so the source of each printed line stays identifiable.
Statements that matter
return fmt.Errorf("retries: want int or string, got %s", raw.Retries)
return fmt.Errorf("retries %q: not a number", s)
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
FAQ
- What is the error handling style?
- By return value: each fallible call hands back an `error`, checked at 4 places here.
- What does Alias Trick Extends UnmarshalJSON print when run?
- Running the file directly is enough — expect labeled output lines such as `rejected:`, `ok: retries=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.