Home > Backend Development > Golang > How to Flatten sql.NullString Output in Go JSON Marshalling?

How to Flatten sql.NullString Output in Go JSON Marshalling?

Patricia Arquette
Release: 2024-11-28 09:58:11
Original
607 people have browsed it

How to Flatten sql.NullString Output in Go JSON Marshalling?

Marshalling sql.NullString: Flattening Output

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.

Solution

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"`
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template