Is there a way, in golang, to see if I can differentiate between a json field being set to null vs a json field not being there when unmarshalled into a struct? Because both set the value in the struct to be nil, but I need to know if the field was there to begin with and to see if someone set it to null.
{
"somefield1":"somevalue1",
"somefield2":null
}
VS
{
"somefield1":"somevalue1",
}
Both jsons will be nil when unmarshalled into a struct. Any useful resources will be very appreciated!
If you unmarshall the object into a map[string]interface{} then you can just check if a field is there
Go Playground
Good question.
I believe you can use https://golang.org/pkg/encoding/json/#RawMessage as:
So after unmarshalling you should have
[]byte("null")
in case ofnull
andnil
if missing.Here is a playground code: https://play.golang.org/p/UW8L68K068
Use
json.RawMessage
to "delay" the unmarshaling process to determine the raw byte before deciding to do something:See the playground https://play.golang.org/p/Wganpf4sbO
By using
github.com/golang/protobuf/ptypes/struct
and jsonpbgithub.com/golang/protobuf/jsonpb
, you can do like this:Output:
If struct field is a pointer, JSON decoder will allocate new variable if the field is present or leave it nil if not. So I suggest to use pointers.