How to Omit Empty Fields in JSON in Go
In Go, you can omit empty fields in JSON output by adding the
omitempty option in your struct field tags like `json:"fieldName,omitempty"`. This tells the JSON encoder to skip fields with zero values such as empty strings, zero numbers, or nil pointers.Syntax
Use the omitempty option in the JSON struct tag to skip fields with empty or zero values during JSON encoding.
Example tag: `json:"fieldName,omitempty"`
- fieldName: the JSON key name
- omitempty: skips the field if it has a zero value (empty string, 0, nil, false, empty slice/map)
go
type Person struct { Name string `json:"name,omitempty"` Age int `json:"age,omitempty"` Address string `json:"address,omitempty"` }
Example
This example shows how fields with empty values are omitted from the JSON output when using omitempty.
go
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name,omitempty"` Age int `json:"age,omitempty"` Address string `json:"address,omitempty"` } func main() { p := Person{Name: "Alice", Age: 0, Address: ""} data, err := json.MarshalIndent(p, "", " ") if err != nil { panic(err) } fmt.Println(string(data)) }
Output
{
"name": "Alice"
}
Common Pitfalls
One common mistake is expecting omitempty to omit fields with non-zero default values like false for booleans or 0 for integers if you want to keep them. Also, omitempty only works with exported fields (capitalized names). Unexported fields are never marshaled.
Another pitfall is using pointers incorrectly. A nil pointer is omitted, but a pointer to a zero value is included.
go
package main import ( "encoding/json" "fmt" ) type Example struct { Flag bool `json:"flag,omitempty"` } func main() { e1 := Example{Flag: false} // zero value, omitted e2 := Example{Flag: true} // included data1, _ := json.Marshal(e1) data2, _ := json.Marshal(e2) fmt.Println(string(data1)) // {} fmt.Println(string(data2)) // {"flag":true} }
Output
{}
{"flag":true}
Quick Reference
- omitempty: skips zero value fields
- Zero values include:
""(empty string),0(numbers),false(bool),nil(pointers, slices, maps) - Only exported fields (capitalized) are marshaled
- Use pointers to omit fields when zero value is valid but you want to omit
nil
Key Takeaways
Add `omitempty` in JSON struct tags to skip empty or zero value fields during encoding.
Only exported (capitalized) struct fields are included in JSON output.
Zero values include empty strings, 0, false, nil pointers, empty slices, and maps.
Use pointers to distinguish between zero values and missing fields.
Without `omitempty`, all fields are included regardless of their value.