Note: This proposal already has as a patch from 2015 by @bakineggs, but it appears to have fallen between the cracks.
I have the following case:
type Join struct {
ChannelId string `json:"channel_id"`
Accounts []Ident `json:"accounts,omitempty"`
History []TextEntry `json:"history,omitempty"`
}
This struct is used for message passing and the slices are only relevant (and set to non-nil) in some cases. However, since encoding/json does not differentiate between a nil slice and an empty slice, there will be legitimate cases where a field is excluded when it's not expected to (e.g., the History slice is set, but empty).
I reiterate the proposal by Dan in his patch referred above to support an omitnil option which allows this differentiation for slices and maps.
Note for hypothetical Go 2.0: This is already how omitempty works for pointers to Go's basic types (e.g., (*int)(nil) is omitted while pointer to 0 is not). For Go 2.0 the behavior of omitempty could change to omit both nil and 0 when specified, and then only nil would be omitted when omitnil is specified.
Note: This proposal already has as a patch from 2015 by @bakineggs, but it appears to have fallen between the cracks.
I have the following case:
This struct is used for message passing and the slices are only relevant (and set to non-
nil) in some cases. However, sinceencoding/jsondoes not differentiate between anilslice and an empty slice, there will be legitimate cases where a field is excluded when it's not expected to (e.g., theHistoryslice is set, but empty).I reiterate the proposal by Dan in his patch referred above to support an
omitniloption which allows this differentiation for slices and maps.Note for hypothetical Go 2.0: This is already how
omitemptyworks for pointers to Go's basic types (e.g.,(*int)(nil)is omitted while pointer to0is not). For Go 2.0 the behavior ofomitemptycould change to omit bothniland0when specified, and then onlynilwould be omitted whenomitnilis specified.