Skip to content

Golang JSON: How to Make a Field Optional (omitempty)

Tags in struct definition are useful when you want to convert structs to other types, especially JSON. Just use the omitempty in front of the field you want to ignore if the value of it is empty (zero value):

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type User struct {
	Name  string
	Age   int
	Title string `json:"title,omitempty"` // ignore this field for marshaling if is empty
}

func main() {
	// Age and Title are empty
	user := User{
		Name: "Morteza",
	}

	jsonBlob, err := json.MarshalIndent(user, "", " ")
	if err != nil {
		log.Fatalf("failed to marshal: %s", err)
	}

	fmt.Println(string(jsonBlob))
}

Leave a Reply

Your email address will not be published. Required fields are marked *