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

Add 'required' struct tag for decoding #393

Open
FeldrinH opened this issue Aug 22, 2022 · 1 comment
Open

Add 'required' struct tag for decoding #393

FeldrinH opened this issue Aug 22, 2022 · 1 comment

Comments

@FeldrinH
Copy link

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

type Entity struct {
    Name: string `json:",required"`
    Active: *boolean `json:",required"`
}

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 {}.
@FeldrinH
Copy link
Author

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)

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

No branches or pull requests

2 participants