-
Notifications
You must be signed in to change notification settings - Fork 18k
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
proposal: encoding/json: allow skipping field by returning an error in MarshalJSON() ([]byte, error)
#57554
Comments
I recently stumbled across the same issue, and also thought that having a error to skip a field would be something nice to have. For now you can use a pointer to a type with type MyStruct struct {
value *string `json:",omitempty"`
} encoding/Json docs:
I think that it would be nice to have something like |
FYI, changes to the JSON package should probably be raised at https://github.com/go-json-experiment/json since AFAICT, that repo is being experimentally primed to replace the existing JSON package. |
Duplicate of #50480 |
Thanks for the tip, it's just a shame that a simple thing like this has to be achieved by introducing more risks and headache for the developer by introducing pointers. But it's the solution we have to go with for the time being at least.
Thank you, I weren't aware of that 👍
That was itself marked as a duplicate as mentioned by rsc:
But I couldn't find any link to the duplicate he was referring to or reasoning for closing, would you mind sharing if you have that available? |
This proposal is a duplicate of a previously discussed proposal, as noted above, |
With the introduction of generics I have started using the following pattern to properly deal with PATCH requests by clients.
This allows me to differentiate between zero values and non-set json fields. This field has a unique
UnMarshaler
andMarshaler
The issue is that if I choose to UnMarshal the
MyStruct
when thevalue
field hasIsSet=false
I would end up with the following JSON:{"value":""}
rather than{}
.I propose the ability to return a specific error
json.ErrSkipField
from theMarshalJSON
that would cause the field to be skipped. This simplifies handling in these scenarios, and allow the logic to hide/show the struct live together with the implementation.Writing a custom
MarshalJSON
function for every struct that happens to use theField
will quickly get tiring and introduce risk of errors.The text was updated successfully, but these errors were encountered: