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

How to Flatten sql.NullString JSON Output in Go?

Patricia Arquette
Release: 2024-12-03 00:19:12
Original
1074 people have browsed it

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

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

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

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

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

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

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)
Copy after login
{
    "id": "68",
    "abn": "SomeABN"
}
Copy after login
Copy after login

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!

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