Home > Backend Development > Golang > How to Efficiently Handle SQL NULL Values and Their JSON Representation in Go?

How to Efficiently Handle SQL NULL Values and Their JSON Representation in Go?

Mary-Kate Olsen
Release: 2025-01-03 06:22:39
Original
253 people have browsed it

How to Efficiently Handle SQL NULL Values and Their JSON Representation in Go?

Working with SQL NULL Values and JSON in an Efficient Manner

In this article, we address the dilemma of working with SQL NULL values in Go and how to handle their JSON representation effectively.

When utilizing Go types such as int64 and string, null values cannot be directly stored. However, we can employ sql.NullInt64 and sql.NullString for this purpose. However, when these types are embedded in a struct and converted to JSON using the json package, the resulting format deviates from the one obtained when using the regular int64 and string types.

This disparity arises because the JSON representation of sql.Null*** types includes an additional level due to these types essentially being structs themselves. As a result, the need arises for a workaround to achieve the desired JSON format.

Instead of abandoning the use of NULL values in the SQL database, one viable solution is to create a custom type that implements the json.Marshaller and json.Unmarshaler interfaces. By embedding the sql.NullInt64 type, we retain the SQL methods while gaining control over the JSON handling. Here's an example demonstrating this approach:

type JsonNullInt64 struct {
    sql.NullInt64
}

func (v JsonNullInt64) MarshalJSON() ([]byte, error) {
    if v.Valid {
        return json.Marshal(v.Int64)
    } else {
        return json.Marshal(nil)
    }
}

func (v *JsonNullInt64) UnmarshalJSON(data []byte) error {
    // Unmarshalling into a pointer will let us detect null
    var x *int64
    if err := json.Unmarshal(data, &x); err != nil {
        return err
    }
    if x != nil {
        v.Valid = true
        v.Int64 = *x
    } else {
        v.Valid = false
    }
    return nil
}
Copy after login

By utilizing this custom type in place of sql.NullInt64, the JSON representation aligns with the desired format.

To demonstrate this solution, you can run the following code in a Go playground:

func main() {
    type Person struct {
        Age     int64                `json:"age"`
        AgeJson JsonNullInt64        `json:"ageJson"`
    }
    p := Person{
        Age:     10,
        AgeJson: sql.NullInt64{Int64: 0, Valid: true},
    }
    b, _ := json.Marshal(p)
    fmt.Println(string(b))
}
Copy after login

The output will resemble the following:

{"age":10,"ageJson":10}
Copy after login

This approach allows for the seamless handling of NULL values in both SQL and JSON, maintaining consistency in data representation.

The above is the detailed content of How to Efficiently Handle SQL NULL Values and Their JSON Representation 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