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

How to Flatten sql.NullString Output When Marshaling JSON in Go?

Barbara Streisand
Release: 2024-11-30 02:18:10
Original
222 people have browsed it

How to Flatten sql.NullString Output When Marshaling JSON in Go?

Flattening sql.NullString Output During JSON Marshaling

When marshaling a Go struct containing an sql.NullString field, the default output includes the field's Valid and String properties. To achieve a flattened output that only includes the value, you must take additional steps.

Consider the following struct:

type Company struct {
    ID   int             `json:"id"`              
    Abn  sql.NullString  `json:"abn,string"`
}
Copy after login

Marshalling this struct with json.Marshal produces an output that looks like:

{
    "id": "68",
    "abn": {
        "String": "SomeABN",
        "Valid": true
    }
}
Copy after login

Extend sql.NullString for Custom JSON Marshaling

To flatten this output, you must extend sql.NullString and implement json.Marshaler.

type NullString sql.NullString

func (x *NullString) MarshalJSON() ([]byte, error) {
    if !x.Valid {
        x.Valid = true
        x.String = ""
        //return []byte("null"), nil
    }
    return json.Marshal(x.String)
}
Copy after login

Define a Custom Type for Flattened Output

Next, define a custom type that embeds the extended NullString and implements json.Marshaler.

type MyNullString struct {
    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

By using this custom type, the marshaled output becomes:

{
    "id": "68",
    "abn": "SomeABN"
}
Copy after login

The above is the detailed content of How to Flatten sql.NullString Output When Marshaling JSON in Go?. 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