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!

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.