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
Barbara StreisandOriginal
2024-11-30 02:18:10240browse

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"`
}

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

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

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)
}

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"`
}

By using this custom type, the marshaled output becomes:

{
    "id": "68",
    "abn": "SomeABN"
}

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!

Statement:
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