Is it possible to only use omitempty when an object is nil and not when it's an empty array?
I would like for the JSON marshaller to not display the value when an object is nil, but show object: [] when the value is an empty list.
objects: nil
{
...
}
objects: make([]*Object, 0)
{
...
"objects": []
}
You will need to create a custom json Marshal/Unmarshal functions for your struct. something like:
// Hello
type Hello struct {
World []interface{} `json:"world,omitempty"`
}
// MarshalJSON()
func (h *Hello) MarshalJSON() ([]byte, error) {
var hello = &struct {
World []interface{} `json:"world"`
}{
World: h.World,
}
return json.Marshal(hello)
}
// UnmarshalJSON()
func (h *Hello) UnmarshalJSON(b []byte) error {
var hello = &struct {
World []interface{} `json:"world"`
}{
World: h.World,
}
return json.Unmarshal(b, &hello)
}
Output:
{"world":[]}
Run above example: https://goplay.tools/snippet/J_iKIJ9ZMhT
t := []string{}
json, _ := json.Marshal(struct {
Data *[]string `json:"data,omitempty"`
}{Data: &t})
fmt.Println(string(json)) // Output: {"data":[]}
https://go.dev/play/p/ZPI39ioU-p5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With