How to Use omitempty in Go

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}

That’s it!