Struct tags for JSON
Tags control JSON field names:
type Config struct {
APIKey string `json:"api_key"`
Debug bool `json:"debug"`
}
json:"api_key" maps the Go field APIKey to the JSON key api_key. Use - to skip a field.
Marshal and unmarshal
The pair works together:
bytes, _ := json.Marshal(v) // struct -> JSON
var v2 T
json.Unmarshal(bytes, &v2) // JSON -> struct
Always handle the returned error, malformed JSON fails decoding. Use Indent for readable output.