Using omitempty in Go JSON Struct Tags
Master the omitempty tag option in Go to control which fields appear in JSON output. Learn zero values, pointer semantics, and common pitfalls.
Detailed Explanation
The omitempty Tag in Go
The omitempty option tells Go's JSON encoder to skip a field if it holds its zero value. This produces cleaner, smaller JSON output.
Zero Values by Type
| Type | Zero Value |
|---|---|
string |
"" |
int, float64 |
0 |
bool |
false |
| pointer | nil |
| slice, map | nil (not empty) |
| struct | never omitted |
Example
type User struct {
Name string `json:"name"`
Email string `json:"email,omitempty"`
Age int `json:"age,omitempty"`
Verified bool `json:"verified,omitempty"`
Bio *string `json:"bio,omitempty"`
}
If Email is "", Age is 0, and Verified is false, marshaling produces:
{ "name": "Alice" }
The Bool and Zero Pitfall
A common mistake: if false or 0 are valid values in your domain (e.g., a boolean flag that can legitimately be false), omitempty will hide them. The solution is to use a pointer type:
Verified *bool `json:"verified,omitempty"`
Now nil means "not provided" and is omitted, while false is a valid value and will be included.
Structs Are Never Omitted
omitempty on a struct field has no effect — an empty struct {} is always included. Use a pointer to the struct if you need omit behavior:
Address *Address `json:"address,omitempty"`
When to Use omitempty
Use it for optional fields in PATCH requests, sparse response objects, and anywhere the absence of a field carries meaning. Avoid it for fields where zero is a valid, meaningful value.
Use Case
PATCH endpoints in REST APIs often send only changed fields. Using omitempty on your request struct ensures that unchanged fields are not included in the JSON body, preventing accidental overwrites.