json.Marshal encodes a Go value as JSON bytes, making Go structs usable in configuration tools and other systems that exchange JSON data. Struct tags map Go fields to JSON keys, while exported fields remain accessible to encoding/json. section 10.5.1
Practical serialization depends on a few design choices:
- Define a Go struct that mirrors the JSON shape, using tags such as `json:"name"`, `omitempty`, or `-` to rename, omit, or exclude fields. section 10.5.1
- Implement `MarshalJSON` when serialized output needs custom behavior, such as redacting a sensitive field before delegating to `json.Marshal`. section 10.5.1
- Use the Go struct as an intermediate representation when converting between JSON and XML, validating and normalizing data before marshaling the requested format. section 10.5.2
Redacting a configuration field during marshaling
A `Config` value can implement `MarshalJSON` by copying its fields into an anonymous struct, replacing `Host` with `"[REDACTED]"`, and returning `json.Marshal(temp)`. The anonymous struct prevents recursive calls to the custom method while preserving the desired JSON keys. 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 the concrete JSON configuration shape that the Go `Config` structure represents. section 10.5.1
