liveBook · Manning

UnmarshalJSON

As explained in Go in Action, Second Edition

UnmarshalJSON is a method convention that customizes how JSON data is decoded into a Go value.

UnmarshalJSON is a method convention that lets a Go type control how JSON bytes become a value. It is useful when ordinary field mapping must include validation or transformation, such as requiring Config.Host to contain a valid URL. section 10.5.1

Implement custom decoding by following this pattern:

  • Define UnmarshalJSON on the receiving type. section 10.5.1
  • Decode into a temporary anonymous struct with JSON tags, avoiding recursive calls to the method. section 10.5.1
  • Validate or transform the temporary fields and return parsing errors immediately. section 10.5.1
  • Assign the validated temporary value to the receiver. section 10.5.1

Validate a configuration host

func (c *Config) UnmarshalJSON(b []byte) error { temp := struct { Name string `json:"name"` Version string `json:"version"` Debug bool `json:"debug"` Port int `json:"port"` Host string `json:"host"` }{} if err := json.Unmarshal(b, &temp); err != nil { return err } if _, err := url.ParseRequestURI(temp.Host); err != nil { return fmt.Errorf("invalid Host URL: %v", err) } *c = Config(temp) return nil } section 10.5.1

Listing 10.16 config.json: Configuration defined in JSON format
{
    "name": "myapp",
    "version": "1.0.0",
    "debug": false,
    "port": 8080,
    "host": "localhost"
}

Use the configuration JSON example to trace ordinary field decoding before adding custom Host validation. section 10.5.1

How Go in Action, Second Edition covers it

How deep it goes
Implements parsing, recursion avoidance, URL validation, error propagation, and receiver assignment through a complete method example.
Examples
Uses a Config value whose Host field is parsed as a URL during decoding.
What it assumes
Assumes Go structs, JSON tags, json.Unmarshal, methods, and basic error handling.
What you can do after
Build custom JSON decoding that returns parsing errors and rejects invalid configuration values before application use.
How it connects
Connects encoding/json, JSON struct tags, Unmarshaler, MarshalJSON, Marshaler, and validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.