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.

GoData Integrity

Code

gosnippet
33 lines
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

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:`.