0

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)

DevK
  • 9,597
  • 2
  • 26
  • 48
  • RE your comment on Tiago's answer: once the custom marshaller on `ChildMap` kicks in it's already too late to omit. You can't return "nothing" at that point. So either custom marshalling on the parent struct, or using `*ChildMap` are valid solutions – blackgreen Apr 11 '22 at 19:55
  • [this](https://stackoverflow.com/questions/46265751/omitting-json-for-empty-custom-type) is also relevant (the question in particular) – blackgreen Apr 11 '22 at 20:00

1 Answers1

0

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"`
}
Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35
  • I'm fine with custom marshalling solution, as long as it's on `ChildMap` and not the parent. I got it to work by making `ChildMap` a pointer (see https://go.dev/play/p/dxKsBMu3zYb), but I'm wondering if there's a way without making it a pointer – DevK Apr 11 '22 at 19:26