The encoding/json exposes a forgiving parser. Every not present property is simply set to its default value. Is there a better way to make a field required than using bulky switch statments and check every field for its default value? Another problem is that not all default types are nil. Is there another way to distinguish between than a not set field and e.g. 0 other than using pointers to be able to check against nil?
Asked
Active
Viewed 641 times
1
-
Maybe we can see the struct you are using to unmarshal(?) json? – vahdet Jan 31 '18 at 14:29
-
Unmarshal to `map[string]interface{}` and bind the struct manually would solve both problem. – leaf bebop Jan 31 '18 at 14:31
-
@vahdet Sorry, but I can't understand why that would help to solve the problems. – Jan 31 '18 at 15:41
-
@leafbebop Thanks, but that would but I would end up with even more boilerplate code. – Jan 31 '18 at 15:42
-
Are you maybe looking for `omitempty`? https://stackoverflow.com/questions/24216510/empty-or-not-required-struct-fields-in-golang – Jack Gore Jan 31 '18 at 16:28
-
@JackGore No, is the question not clear? – Jan 31 '18 at 16:38
1 Answers
0
You may look at what there is available to implement so-called "JSON schema validation".
You may start with this search
which yields github.com/juju/gojsonschema among others;
while I have no idea about its quality, it's used as part of
Ubuntu's Juju cloud orchestration solution so I'd expect it
to be battle tested. Still, caveat emptor.
kostix
- 51,517
- 14
- 93
- 176