Optional JSON fields can be included only when a value is present.

Optional Fields

optional_fields.go
package main

import (
	"fmt"
	"strings"
)

type Profile struct {
	Name  string `json:"name"`
	Email string `json:"email,omitempty"`
}

func main() {
	var includeEmail = 
	profile := Profile{Name: "Mina"}

	if includeEmail {
		profile.Email = "mina@example.com"
	}

	text := `{"name":"` + profile.Name + `"}`
	if profile.Email != "" {
		text = `{"name":"` + profile.Name + `","email":"` + profile.Email + `"}`
	}

	hasEmail := strings.Contains(text, "email")
	fmt.Println("includeEmail=", includeEmail)
	fmt.Println("hasEmail=", hasEmail)
	fmt.Println("json=", text)
}
package main

import (
	"fmt"
	"strings"
)

type Profile struct {
	Name  string `json:"name"`
	Email string `json:"email,omitempty"`
}

func main() {
	var includeEmail = 
	profile := Profile{Name: "Mina"}

	if includeEmail {
		profile.Email = "mina@example.com"
	}

	text := `{"name":"` + profile.Name + `"}`
	if profile.Email != "" {
		text = `{"name":"` + profile.Name + `","email":"` + profile.Email + `"}`
	}

	hasEmail := strings.Contains(text, "email")
	fmt.Println("includeEmail=", includeEmail)
	fmt.Println("hasEmail=", hasEmail)
	fmt.Println("json=", text)
}
optional field An optional JSON field can be present for one value and absent for another while the Go type stays the same.