Home >Backend Development >Golang >How to Flatten JSON Output from a Go struct containing sql.NullString?
Given a Go struct containing a sql.NullString, marshaling the struct using encoding/json produces a nested object instead of the desired flattened value.
type Company struct { ID int `json:"id"` Abn sql.NullString `json:"abn,string"` }
For instance, marshaling such a struct results in output like:
{ "id": "68", "abn": { "String": "SomeABN", "Valid": true } }
However, the desired output is flattened:
{ "id": "68", "abn": "SomeABN" }
Customizing the MarshalJSON method for the NullString type by defining a new type allows for a more controlled output.
type MyNullString struct { sql.NullString } func (s MyNullString) MarshalJSON() ([]byte, error) { if s.Valid { return json.Marshal(s.String) } return []byte(`null`), nil } type Company struct { ID int `json:"id"` Abn MyNullString `json:"abn,string"` }
By implementing the json.Marshaler interface, the MyNullString type can control how it is represented as JSON. When it is non-null, it returns the underlying string, and for null values, it returns a literal "null" string.
The example provided in the code playground demonstrates the desired behavior:
https://play.golang.org/p/Ak_D6QgIzLb
This solution flattens the output by ignoring the Valid field and returning the string value directly.
The above is the detailed content of How to Flatten JSON Output from a Go struct containing sql.NullString?. For more information, please follow other related articles on the PHP Chinese website!