25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Using omitempty in Go JSON Marshaling
Code Snippet

Using omitempty in Go JSON Marshaling

go

The omitempty struct tag option allows you to exclude fields with empty values from the JSON output. This is useful for reducing JSON payload size and keeping responses clean when certain optional fields are not set. When a field’s value matches the zero value for its type (empty string, zero for numbers, false for booleans, etc.), it will be omitted from the marshalled JSON.

By adding omitempty to your struct tags, you make it easy to handle optional fields in APIs and configuration files. This pattern is common in REST APIs where you want to only include fields that have meaningful values. It keeps JSON responses concise and makes it clear which fields are required versus optional.

You can combine omitempty with other tag options like string to control both marshalling behavior and field inclusion. The tag format follows the pattern json:"fieldname,options", where multiple options are comma-separated.

Further Reading: