You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It would be useful to add support for a struct tag indicating required fields, for example json:",required", which if present would cause the decoder to return an error if the field is missing in the input json. If the field is present, the decoder would behave the same encoding/json.
would return an error with both {"active": true} as well as {"name": "Name"}, but not {"name": "Name", "active": null}
This would be useful to ensure that important fields are explicitly set in the json while allowing the default value to be valid.
The current common workaround as far as I know is to turn all the fields into pointers and then validate that they aren't nil.
This has several drawbacks:
The default value of your struct is now invalid.
Outside of json decoding you have to constantly keep in mind that despite the fields being pointers, nil values are not valid.
This doesn't work if you need to allow for example {"value": null}, but not {}.
The text was updated successfully, but these errors were encountered:
As an alternative, if adding a struct tag seems like too much of a break away from encoding/json, an alternative proposal would be to add a config option similar to DisallowUnknownFields that controlls handling of fields missing from the input json data, with three possible modes:
All fields are optional (current behavior)
Only fields with nil as default value, such as pointers and arrays are optional, other fields are required. (this matches the intuitive notion that nil represents a missing value and therefore any field that can't be nil can't be missing)
All fields are required. (this matches the intuitive notion that a struct and its json representation should have exactly the same fields, to ensure there is no ambiguity about any values)
The essential idea is the same as golang/go#17163:
It would be useful to add support for a struct tag indicating required fields, for example
json:",required"
, which if present would cause the decoder to return an error if the field is missing in the input json. If the field is present, the decoder would behave the same encoding/json.So for example
would return an error with both
{"active": true}
as well as{"name": "Name"}
, but not{"name": "Name", "active": null}
This would be useful to ensure that important fields are explicitly set in the json while allowing the default value to be valid.
The current common workaround as far as I know is to turn all the fields into pointers and then validate that they aren't nil.
This has several drawbacks:
{"value": null}
, but not{}
.The text was updated successfully, but these errors were encountered: