Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring an object in struct is nil and not when it's an empty array

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": []
}
like image 347
KIVOX Avatar asked Feb 13 '26 12:02

KIVOX


2 Answers

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

like image 66
twiny Avatar answered Feb 16 '26 05:02

twiny


    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

like image 29
MadRac Avatar answered Feb 16 '26 07:02

MadRac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!