« Back to Index

Go: JSON omitempty vs omitzero

View original Gist on GitHub

Tags: #go #json

README.md

Guidelines:

[!TIP] The super quick summary is: use omitzero
Unless you need to identify an empty map/slice/interface, then use omitempty.
If you need to identify if value was deliberately set to the zero type, use a pointer.
If you have specific zero requirements define custom type with IsZero method.

** Go checks if all the struct’s fields are their respective zero values or if it has a custom IsZero() bool method that returns true.

Here is a contrived example of a custom int type that implements IsZero to trick 0 to be shown (but really, the implementation can be whatever makes sense for your application):

package main

import (
	"encoding/json"
	"fmt"
)

type Data struct {
	Field CustomInt `json:"field,omitzero"`
}

type CustomInt int

func (i CustomInt) IsZero() bool {
	return i == -1
}

func main() {
	d1 := Data{}
	j1, _ := json.Marshal(d1)
	fmt.Println(string(j1)) // {"field":0}

	d2 := Data{Field: 0}
	j2, _ := json.Marshal(d2)
	fmt.Println(string(j2)) // {"field":0}

	d3 := Data{Field: 1}
	j3, _ := json.Marshal(d3)
	fmt.Println(string(j3)) // {"field":1}
}