Hello,
I’m looking for a way to retain null values sent from a REST API server in JSON. Currently, I’m using a struct and unmarshal but this turns Nulls into zeros.
Does anyone have a quick code example or link to a good video on this? I tried with pointers but I’m not understanding how it helps, I still see zeros.
Just like NobbZ said, you can use a pointer that indicates that the data might not be present
type Foo struct {
Bar *string `json:"bar"`
}
Just remember that if you are using a value and it might be null you need to make a null check before using the value as a existent value, otherwise you’ll get a panic: runtime error: invalid memory address or nil pointer dereference, you can use something like that:
var foo Foo
//...unmarshall to Foo
if foo.Bar != nil {
// using len() here is safe
fmt.Println(len(*foo.Bar))
}
You might also want to check omitempty and omitzero JSON tags, for cleaning up your JSON outputs, so search a bit about them (omitzero was introduced in go 1.24 so it’s pretty new, you might not find a lot of resources about it)
One nice thing about go is len() being a static function. You don’t need a null check on slices before reading length or even before looping over it. A nil-slice will behave like a slice of length 0 for most purposes.
But you are of course right for all other primitives, structs and maps.