Omitzero Drops Zero Fields In JSON
Use the Go 1.24 omitzero tag to drop zero-valued time.Time structs and custom IsZero() fields — both cases omitempty keeps under its empty-value definition.
Code
package main
import (
"encoding/json"
"fmt"
"time"
)
// IsZero() bool 让类型自己定义零值语义(encoding/json 内部用未导出的 isZeroer 接口识别它)
type Review string
func (r Review) IsZero() bool { return r == "pending" }
type AuditEvent struct {
ID string `json:"id"`
CreatedAt time.Time `json:"created_at,omitempty"` // 结构体零值不在 omitempty 的空值定义里,零值 time.Time{} 会被原样保留
ExpiresAt time.Time `json:"expires_at,omitzero"` // 同一个零值,omitzero 直接省略整个字段
Review Review `json:"review,omitzero"` // "pending" 命中自定义 IsZero,被省略
}
func main() {
// draft:CreatedAt 零值被 omitempty 保留,expires_at(零值)与 review("pending")被 omitzero 省略
draft, _ := json.Marshal(AuditEvent{ID: "a-1024", Review: "pending"})
fmt.Println("draft:", string(draft))
final, _ := json.Marshal(AuditEvent{
ID: "a-2048",
CreatedAt: time.Date(2026, 1, 15, 9, 30, 0, 0, time.UTC),
ExpiresAt: time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC),
Review: "approved",
})
fmt.Println("final:", string(final))
}How it works
Omitzero Drops Zero Fields In JSON keeps everything in the functions IsZero and main.
Putting it to use
What the file revolves around: func (r Review) IsZero() bool
Running the file prints labeled results such as draft:, final: — each operation’s effect is visible in the output.
Core lines under the microscope
func (r Review) IsZero() bool { return r == "pending" }
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- What does Omitzero Drops Zero Fields In JSON print when run?
- Running the file directly is enough — expect labeled output lines such as `draft:`, `final:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.