Home > Backend Development > Golang > How to Handle SQL NULL Values in Go JSON Marshalling?

How to Handle SQL NULL Values in Go JSON Marshalling?

Mary-Kate Olsen
Release: 2025-01-03 01:47:43
Original
969 people have browsed it

How to Handle SQL NULL Values in Go JSON Marshalling?

JSON Handling of SQL NULL Values in Go

When working with nullable SQL data types in Go, the sql.Nullxxx types are often used to allow for null values. However, this can lead to formatting issues when encoding such structures into JSON using the json package.

By default, sql.Nullxxx types are marshaled as objects with an additional level due to their struct nature. This can result in undesired JSON output. To address this, consider implementing the json.Marshaller and json.Unmarshaler interfaces for a custom type that embeds the sql.Nullxxx type.

For example, the following JsonNullInt64 type can be used for encoding sql.NullInt64 values as null or integers:

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 {
    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

When using the JsonNullInt64 type, it will be encoded in the expected manner, allowing for proper JSON representation without the additional level.

The above is the detailed content of How to Handle SQL NULL Values in Go JSON Marshalling?. 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