'How to omit map from JSON marshalling only when it's empty? [duplicate]

I need to return an empty json {} when the map is not nil, but it's empty. When the map is nil I need it to be omitted.

How could I go about doing this?

type ChildMap map[string]string

type Parent struct {
    ID int64
    T  ChildMap `json:"t,omitempty"`
}

Here's a playground that explains what I'm trying to do quite well:

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

In 1st case it needs to be omitted (this works), 2nd case I need it returned as {} (doesn't work), 3rd case needs to be displayed (also works)

go


Solution 1:[1]

I had the same requirement long ago and this was the only solution.

Set your Slice on Bar and even with no elements it will render []

A more interesting solution need a specific Unmarshal code (perhaps is more readable than this)

type Foo struct {
    Bar      *interface{} `json:"bar,omitempty"`
    Baz *interface{} `json:"baz,omitempty"`
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tiago Peczenyj