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
Release: 2024-12-02 19:20:13
Original
652 people have browsed it

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

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

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

However, the desired output is flattened:

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

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

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
Copy after login

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!

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