Home >Backend Development >Golang >How to Flatten JSON Output from a Go struct containing sql.NullString?

How to Flatten JSON Output from a Go struct containing sql.NullString?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 19:20:13572browse

How to Flatten JSON Output from a Go struct containing sql.NullString?

Marshaling sql.NullString for Flattened Output

Problem

Given a Go struct containing a sql.NullString, marshaling the struct using encoding/json produces a nested object instead of the desired flattened value.

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

For instance, marshaling such a struct results in output like:

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

However, the desired output is flattened:

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

Solution

Customizing the MarshalJSON method for the NullString type by defining a new type allows for a more controlled output.

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 implementing the json.Marshaler interface, the MyNullString type can control how it is represented as JSON. When it is non-null, it returns the underlying string, and for null values, it returns a literal "null" string.

The example provided in the code playground demonstrates the desired behavior:

https://play.golang.org/p/Ak_D6QgIzLb

This solution flattens the output by ignoring the Valid field and returning the string value directly.

The above is the detailed content of How to Flatten JSON Output from a Go struct containing sql.NullString?. 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