Home >Backend Development >Golang >How to Handle SQL NULL Values and JSON Effectively in Go?
Working with SQL NULL Values and JSON in Go
When working with nullable values in Go, it's common to use types like sql.NullInt64 and sql.NullString. However, these types can lead to unexpected results when generating JSON from a struct that contains them. Specifically, the JSON output may include an additional level because sql.Null*** is also a struct.
Workaround
To address this issue, one workaround is to create a custom type that implements the json.Marshaller and json.Unmarshaler interfaces. By embedding the sql.NullInt64 type, you can seamlessly handle SQL methods while defining your own JSON marshaling and unmarshaling behavior.
Here's an example:
type JsonNullInt64 struct { sql.NullInt64 } func (v JsonNullInt64) MarshalJSON() ([]byte, error) { if v.Valid { return json.Marshal(v.Int64) } else { return json.Marshal(nil) } } func (v *JsonNullInt64) UnmarshalJSON(data []byte) error { // Unmarshalling into a pointer will let us detect null var x *int64 if err := json.Unmarshal(data, &x); err != nil { return err } if x != nil { v.Valid = true v.Int64 = *x } else { v.Valid = false } return nil }
When using this custom type instead of sql.NullInt64, the JSON output will be in the format you expect, without the additional level.
Example
You can test this example at the following link:
http://play.golang.org/p/zFESxLcd-c
The above is the detailed content of How to Handle SQL NULL Values and JSON Effectively in Go?. For more information, please follow other related articles on the PHP Chinese website!