Home >Backend Development >Golang >How to Handle Null int64 Values When Parsing JSON in Go?
Parsing JSON with int64 Null Values in Go
When parsing JSON data containing int64 values, it's possible to encounter null values. By default, the Go encoding/json package attempts to unmarshal null values directly into int64 fields, resulting in an error as it cannot convert null to int64.
To resolve this issue, consider using pointers instead of direct int64 fields. Pointers can be nil or point to an int64 with an associated value. Here's an example:
import ( "encoding/json" "fmt" ) var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`) type jsonobj struct{ World []World } type World struct{ Data *int64 } func main() { var data jsonobj jerr := json.Unmarshal(d, &data) fmt.Println(jerr) if data.World[1].Data != nil { fmt.Println(*data.World[1].Data) } }
By using a pointer, the data field in the World struct can either be nil if the JSON value is null or point to an int64 value otherwise. This allows us to handle null values gracefully without errors.
The above is the detailed content of How to Handle Null int64 Values When Parsing JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!