Omitmepty in Golang

My computer develop environment

1
2
3
4
5
6
7
$ sw_vers 
ProductName: Mac OS X
ProductVersion: 10.12.6
BuildVersion: 16G29

$ go version
go version go1.8.3 darwin/amd64

Omitempty Behavior

We often use json to serialize an object. In some scenarios, we only need to pass a property with a value. At this time we will use the omitempty property.

Read the official documentation for the encoding/json package and we will find a description of the omitempty behavior:

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless

the field’s tag is “-“, or
the field is empty and its tag specifies the “omitempty” option.
The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object’s default key string is the struct field name but can be specified in the struct field’s tag value. The “json” key in the struct field’s tag value is the key name, followed by an optional comma and options. Examples:

The role of omitempty is to ignore this field when serializing JSON when the value of a field is empty.

What needs to be noted here is the definition of empty.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

A simple example will help better understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
"encoding/json"
)

type people struct {
Name string `json:"name"`
AccountBalance float32 `json:"balance"`
}

func main() {

p := new(people)
p.Name = "liyuliang"

json,_ := json.Marshal(p)
println(string(json))
}

The result is that my account balance is 0.

1
{"name":"liyuliang","money":0}

When the property AccountBalance is added with omitempty

1
2
3
4
type people struct {
Name string `json:"name"`
Money float32 `json:"money,omitempty"`
}

I don’t even have an account!!

1
{"name":"liyuliang"}

What a impressive property! Isn’t it?

Share