JSON: omitzero
In Go version 1.24
that will be release around February 2025 there is a feature that very useful in my opinion. That is new json tag option omitzero
.
The "omitzero" option specifies that the field should be omitted from the encoding if the field has a zero value, according to rules:
If the field type has an "IsZero() bool" method, that will be used to determine whether the value is zero.
Otherwise, the value is zero if it is the zero value for its type.
From golang official docs, the field that have omitzero
tags and has zero value by either IsZero()
method or zero value for its type will be excluded.
Let's take an example:
Output:
The problem with omitempty
tag is it only excluded value that are empty eg: false
, 0
, a nil
pointer, a nil
interface value, and any array
, slice
, map
, or string
that has zero length. So if you have a struct field that has empty value it still included even though the field has omitempty
tag, unless we define the field as pointer and make it nil.
Same case with time.Time
where the zero value is "0001-01-01T00:00:00Z"
. With omitempty
it still included even it's zero value.
The omitzero
tag will solve this problem in Go 1.24. We can use golang playground with dev branch version to try this:
Output:
References
Last updated