What is omitempty in Golang

The omitempty in Go is a JSON struct tag option that suggests the field should be omitted from the JSON output when encoding if it has an empty value (e.g., zero value for its type). This can help reduce the size of the resulting JSON and make it more readable by excluding unnecessary fields.

Example

package main

import (
  "encoding/json"
  "fmt"
)

type Person struct {
  Name string `json:"name"`
  Age int `json:"age,omitempty"`
  Occupation string `json:"occupation,omitempty"`
}

func main() {
   person := Person{
      Name: "KB",
      Age: 30,
   }

  jsonData, err := json.Marshal(person)
  if err != nil {
    fmt.Println("Error marshaling JSON:", err)
    return
  }

 fmt.Println("JSON output:", string(jsonData))
}

Output

JSON output: {"name":"KB","age":30}

In this example, we define a Person struct with three fields: Name, Age, and Occupation.

The Age and Occupation fields have the omitempty option in their JSON tags, meaning they will be omitted from the JSON output if they are empty (i.e., have zero values for their respective types).

When we create a Person instance with only a Name and Age and then marshal it using the json.Marshal() function, the Occupation field is omitted from the resulting JSON since it has an empty value (an empty string, in this case).

As you can see, the Occupation field is not present in the JSON output because it did not include in the JSON output.

That’s it.

Leave a Comment