json.Unmarshal decodes a JSON byte slice into a supplied Go value, commonly a pointer to a configuration struct. It checks JSON-to-Go type compatibility and returns an error for malformed or incompatible input. section 10.5.1
Use json.Unmarshal effectively by combining it with:
- Exported struct fields and JSON tags, which map JSON keys such as "port" to Go fields such as Port. section 10.5.1
- Pointers to destination values, allowing decoded data to populate an existing struct. section 10.5.1
- Custom UnmarshalJSON methods, which can reuse json.Unmarshal and add domain validation such as checking a host URL. section 10.5.1
- An intermediate Go struct when converting JSON to another representation, so parsing validates and normalizes the data first. section 10.5.2
Decode a server configuration
Given JSON containing name, version, debug, port, and host fields, define a tagged Config struct and call json.Unmarshal(data, &cfg). Handle the returned error before using cfg; custom unmarshaling can reject an invalid host URL. 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"
}
Inspect a concrete configuration payload containing strings, a Boolean, and an integer before mapping it into Go. section 10.5.1
