Home > Backend Development > Golang > How to Flatten the Output of a Marshalled sql.NullString in Go?

How to Flatten the Output of a Marshalled sql.NullString in Go?

Barbara Streisand
Release: 2024-11-28 07:58:14
Original
321 people have browsed it

How to Flatten the Output of a Marshalled sql.NullString in Go?

How to Flatten and Output Only Value from Marshalled sql.NullString in Go?

Given a Golang struct with a sql.NullString field, the default marshaling behavior results in an output where the field is nested inside a JSON object with String and Valid keys. To achieve a flattened output containing only the value of the NullString, follow these steps:

1. Define a Custom Type:

Create a custom type that embeds sql.NullString and implements the json.Marshaler interface.

type MyNullString struct {
    sql.NullString
}
Copy after login

2. Implement the MarshalJSON Method:

Inside the MyNullString, implement the MarshalJSON method to provide custom JSON marshalling behavior.

func (s MyNullString) MarshalJSON() ([]byte, error) {
    if s.Valid {
        return json.Marshal(s.String)
    }
    return []byte(`null`), nil
}
Copy after login

3. Modify the Struct:

Use the custom MyNullString type for the field in the struct that requires flattening.

type Company struct {
    ID   int          `json:"id"`              
    Abn  MyNullString `json:"abn,string"`
}
Copy after login

Example:

package main

import (
    "database/sql"
    "encoding/json"
    "log"
)

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"`
}

func main() {
    company := Company{
        ID:   68,
        Abn:  MyNullString{String: "SomeABN", Valid: true},
    }

    result, err := json.Marshal(company)
    if err != nil {
        log.Fatal(err)
    }

    // Output: {"id":68,"abn":"SomeABN"}
    log.Println(string(result))
}
Copy after login

By following these steps, you can effectively flatten the output of sql.NullString fields and obtain only the value in your marshalled JSON.

The above is the detailed content of How to Flatten the Output of a Marshalled sql.NullString 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