Home >Backend Development >Golang >How to Flatten the Output of a Marshalled sql.NullString in Go?
Given a Golang struct with a sql.NullString field, the default marshaling behavior results in an output where the field is nested inside a JSON object with String and Valid keys. To achieve a flattened output containing only the value of the NullString, follow these steps:
1. Define a Custom Type:
Create a custom type that embeds sql.NullString and implements the json.Marshaler interface.
type MyNullString struct { sql.NullString }
2. Implement the MarshalJSON Method:
Inside the MyNullString, implement the MarshalJSON method to provide custom JSON marshalling behavior.
func (s MyNullString) MarshalJSON() ([]byte, error) { if s.Valid { return json.Marshal(s.String) } return []byte(`null`), nil }
3. Modify the Struct:
Use the custom MyNullString type for the field in the struct that requires flattening.
type Company struct { ID int `json:"id"` Abn MyNullString `json:"abn,string"` }
Example:
package main import ( "database/sql" "encoding/json" "log" ) 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"` } func main() { company := Company{ ID: 68, Abn: MyNullString{String: "SomeABN", Valid: true}, } result, err := json.Marshal(company) if err != nil { log.Fatal(err) } // Output: {"id":68,"abn":"SomeABN"} log.Println(string(result)) }
By following these steps, you can effectively flatten the output of sql.NullString fields and obtain only the value in your marshalled JSON.
The above is the detailed content of How to Flatten the Output of a Marshalled sql.NullString in Go?. For more information, please follow other related articles on the PHP Chinese website!