Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Golang | Prevent empty values in Marshaled JSON #77

Open
atc0005 opened this issue Mar 31, 2020 · 2 comments
Open

Golang | Prevent empty values in Marshaled JSON #77

atc0005 opened this issue Mar 31, 2020 · 2 comments
Labels

Comments

@atc0005
Copy link
Owner

atc0005 commented Mar 31, 2020

From the documentation:

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

For some fields, even when omitempty is specified the resulting JSON will still contain empty fields.

Examples:

Workaround as noted by golang/go#11939 (comment):

It appears there are only two ways to have omitempty work with a struct.

  • Use a pointer to the struct where the pointer is nil rather than a zero value struct.
  • Implement Marshaler interface for the surrounding type to provide special handling for zero value structs

The later can be somewhat cumbersome to maintain field parity for large structures. The former means data is no longer contiguous and requires care for multi-threaded use.

@atc0005 atc0005 added the golang label Mar 31, 2020
@atc0005
Copy link
Owner Author

atc0005 commented Jun 19, 2020

I believe that I saw this topic mentioned recently, either as Go 1.15 item or perhaps related to Generics?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant