Good day,
I’m on the lookout for a strategy to retain null values despatched from a REST API server in JSON. At the moment, I’m utilizing a struct and unmarshal however this turns Nulls into zeros.
Does anybody have a fast code instance or hyperlink to a superb video on this? I attempted with pointers however I’m not understanding the way it helps, I nonetheless see zeros.
kind foo struct {
Foo *int `json:"foo"`
}
3 Likes
Hello Sivan,
Identical to NobbZ stated, you need to use a pointer that signifies that the information may not be current
kind Foo struct {
Bar *string `json:"bar"`
}
Simply do not forget that in case you are utilizing a worth and it could be null you must make a null verify earlier than utilizing the worth as a existent worth, in any other case you’ll get a panic: runtime error: invalid reminiscence handle or nil pointer dereference, you need to use one thing like that:
var foo Foo
//...unmarshall to Foo
if foo.Bar != nil {
// utilizing len() right here is secure
fmt.Println(len(*foo.Bar))
}
You may also need to verify omitempty
and omitzero
JSON tags, for cleansing up your JSON outputs, so search a bit about them (omitzero
was launched in go 1.24 so it’s fairly new, you may not discover plenty of sources about it)