How to Handle omitempty with Structs, Pointers, and Zero Values

The omitempty tag skips fields only when they are their zero value, requiring pointers for structs to omit based on specific internal states.

The omitempty tag only omits a field from JSON output if the field's value is the zero value for its type, which is nil for pointers and empty strings for strings. For a pointer field, omitempty works as expected because the zero value is nil; for a struct field, it only omits if the entire struct is the zero value (all fields are zero), not if just one field is zero. To omit a struct field based on a specific internal field, you must use a pointer to the struct or implement custom marshaling.

type Config struct {
    // Omitted if ptr is nil
    Ptr *string `json:"ptr,omitempty"`
    
    // Omitted only if the entire struct is zero-valued (Name="", ID=0)
    Info Info `json:"info,omitempty"`
    
    // Omitted if ptrInfo is nil
    PtrInfo *Info `json:"ptrInfo,omitempty"`
}

type Info struct {
    Name string
    ID   int
}