The JSON field is set to zero against a field that is not

Is there a way, in golang, to see if I can distinguish a json field from a null value from a json field that is not there when it is not bound to a structure? Because both set the value in the struct to nil, but I need to know if this field was for starters, and to make sure someone set it to null.

{ "somefield1":"somevalue1", "somefield2":null } 

VS

 { "somefield1":"somevalue1", } 

Both jsons will be zero if they are not combined into a structure. Any useful resources will be greatly appreciated!

+11
json null struct go
source share
5 answers

Use json.RawMessage to β€œdelay” the json.RawMessage process to determine the raw byte before deciding:

 var data = []byte('{ "somefield1":"somevalue1", "somefield2": null }') type Data struct { SomeField1 string SomeField2 json.RawMessage } func main() { d := &Data{} _ = json.Unmarshal(data, &d) fmt.Println(d.SomeField1) if len(d.SomeField2) > 0 { if string(d.SomeField2) == "null" { fmt.Println("somefield2 is there but null") } else { fmt.Println("somefield2 is there and not null") // Do something with the data } } else { fmt.Println("somefield2 doesn't exist") } } 

See the playground https://play.golang.org/p/Wganpf4sbO

+9
source share

If you unmount the object in the map interface [string] {}, you can simply check if there is a field there

 type unMarshalledObject map[string]interface{} json.Unmarshall(input, unMarshhaledObject) _, ok := unMarshalledObject["somefield2"] 

Go to the site

+4
source share

Good question.

I believe you can use https://golang.org/pkg/encoding/json/#RawMessage like:

 type MyMessage struct { somefield1 string somefield2 json.RawMessage } 

So, after unmarshalling you should have []byte("null") in case of null and nil if they are absent.

Here is the playground code: https://play.golang.org/p/UW8L68K068

+4
source share

If the struct field is a pointer, the JSON decoder will allocate a new variable if this field is present or leave it null if not. Therefore, I suggest using pointers.

 type Data struct { StrField *string IntField *int } ... if data.StrField != nil { handle(*data.StrField) } 
0
source share

Using github.com/golang/protobuf/ptypes/struct and jsonpb github.com/golang/protobuf/jsonpb you can do the following:

 func TestFunTest(t *testing.T) { p := &pb.KnownTypes{} e := UnmarshalString(`{"val":null}`, p) fmt.Println(e, p) p = &pb.KnownTypes{} e = UnmarshalString(`{"val":1}`, p) fmt.Println(e, p) p = &pb.KnownTypes{} e = UnmarshalString(`{"val":"string"}`, p) fmt.Println(e, p) p = &pb.KnownTypes{} e = UnmarshalString(`{}`, p) fmt.Println(e, p) } 

Output:

 [ `go test -test.run="^TestFunTest$"` | done: 1.275431416s ] <nil> val:<null_value:NULL_VALUE > <nil> val:<number_value:1 > <nil> val:<string_value:"string" > <nil> PASS 
0
source share

All Articles