When marshalling a Go struct with a sql.NullString field, it's possible to encounter an output JSON with a nested object representing the NullString. However, this nested representation may not be desirable.
To flatten the output and display only the value, create a custom type that embeds sql.NullString and implements the json.Marshaler interface.
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"` }
This custom type provides a MarshalJSON method that checks if the NullString value is valid. If it is, it marshals the string value. Otherwise, it marshals null.
By using this custom type and applying it to the Abn field in the Company struct, the JSON output will be flattened, displaying only the Abn value and omitting the nested object.
The above is the detailed content of How to Flatten sql.NullString Output in Go JSON Marshalling?. For more information, please follow other related articles on the PHP Chinese website!