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

How to Flatten sql.NullString JSON Output in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 00:19:12987browse

How to Flatten sql.NullString JSON Output in Go?

Custom Marshaling for Flattened sql.NullString Output

When marshalling a sql.NullString field in a Go struct using json.Marshal, the default output includes additional metadata such as Valid and String fields. This behavior may not be desired in certain scenarios where the flattened value is preferred.

Consider the following struct:

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

When marshaling this struct, the result will resemble the following:

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

However, the desired outcome is a flattened version with just the value:

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

Custom Marshaller Implementation

To achieve this, it is necessary to implement a custom type that embeds sql.NullString and implements the json.Marshaler interface. This custom type can define its own marshalling behavior through the MarshalJSON method.

Here's an example:

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

By using the custom MyNullString type, the marshalling will now produce the desired flattened result:

company := &Company{}
company.ID = 68
company.Abn.String = "SomeABN"
result, err := json.Marshal(company)
{
    "id": "68",
    "abn": "SomeABN"
}

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