When unmarshaling a json post into a struct, missing fields for bools will always unmarshal to a false value.
Is there a way to detect if there are missing fields in the json post data?
Thanks in advance.
When unmarshaling a json post into a struct, missing fields for bools will always unmarshal to a false value.
Is there a way to detect if there are missing fields in the json post data?
Thanks in advance.
I think you’re looking for something like the inverse of this - https://godoc.org/github.com/clbanning/checkjson#Validate.
Not hard to implement - what do you want back? Just a []string of the struct members that don’t have matching JSON keys/tags in the JSON object?
Maybe switch from a bool to a *bool might help you.
func main() {
type test struct {
Field1 *bool `json: "field1"`
}
var test1, test2, test3 test
json.Unmarshal([]byte(`{"field1": true}`), &test1)
fmt.Println(test1.Field1, *test1.Field1) // 0xc82000a388 true
json.Unmarshal([]byte(`{"field1": false}`), &test2)
fmt.Println(test2.Field1, *test2.Field1) // 0xc82000a3a8 false
json.Unmarshal([]byte(`{}`), &test3)
fmt.Println(test3.Field1) // <nil>
}
If you just want to “hide” the missing fields, you could probably use the omitempty
notation in your struct, like:
SomeData string `json:",omitempty"`
Thanks for the responses chaps. Helps a lot.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.