Search code examples
jsongomarshalling

Got empty struct even in omitempty tag


I have used the same struct for inline and nested in the main struct with omitempty tag. Since I'm not assigning any values in the keys I get the empty struct in JSON. Can anyone help me in this case?

package main

import (
    "encoding/json"
    "fmt"
)

type Customer struct {
    Name              string `json:"name,omitempty" bson:"name"`
    Gender            string `json:"gender,omitempty" bson:"gender"`
    Address           `json:",inline" bson:",inline" `
    OptionalAddresses []Address `json:"optionalAddresses,omitempty" bson:"optionalAddresses"`
}

type Address struct {
    Country    string `json:"country,omitempty" bson:"country"`
    ZoneDetail Zone   `json:"zone,omitempty" bson:"zone"`
}

type Zone struct {
    Latitude  float64 `json:"lat,omitempty" bson:"lat,omitempty"`
    Longitude float64 `json:"lon,omitempty" bson:"lon,omitempty"`
}

func main() {
    cust := Customer{Name: "abc", Gender: "M"}

    dataByt, _ := json.Marshal(cust)
    fmt.Println(string(dataByt))
}

Output:

{"name":"abc","gender":"M","zone":{}}

https://go.dev/play/p/aOlbwWelBS3


Solution

  • 'omitempty' is omit a field if the field value is empty. But in Golang we do not have empty value for struct and you can use pointer to struct (in your case *Zone) instead.

    ...
    
    type Address struct {
        Country    string `json:"country,omitempty" bson:"country"`
        ZoneDetail *Zone   `json:"zone,omitempty" bson:"zone"`
    }
    
    ...