Home  >  Article  >  Backend Development  >  How to Marshal a []byte Field as a String in Go JSON Encoding?

How to Marshal a []byte Field as a String in Go JSON Encoding?

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 03:29:021017browse

How to Marshal a []byte Field as a String in Go JSON Encoding?

Marshaling JSON []byte as Strings in Go

When encoding a struct containing []byte fields into JSON, an unexpected string representation may result. In this encoding, the []byte field is marshaled as a base64-encoded string, as stated in the documentation:

"Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object."

To illustrate this behavior, consider the following Msg struct:

<code class="go">type Msg struct {
    Content []byte
}</code>

In the following example, the string "Hello" is converted to a []byte slice helloSlc and assigned to the Content field of the obj Msg object:

<code class="go">helloStr := "Hello"
helloSlc := []byte(helloStr)
obj := Msg{helloSlc}</code>

Upon encoding obj to JSON using json.Marshal, the resulting JSON contains the base64-encoded string representation of the []byte field:

<code class="go">json, _ := json.Marshal(obj)
fmt.Println(string(json))</code>

Output:

{"Content":"SGVsbG8="}

To obtain the original string value "Hello" in the JSON output, the []byte field needs to be explicitly decoded from its base64-encoded representation before encoding to JSON. This can be achieved using the encoding/base64 package:

<code class="go">import (
    "encoding/base64"
    "encoding/json"
    "fmt"
)

type Msg struct {
    Content string
}

func main() {
    helloSlc := []byte("Hello")
    obj := Msg{string(base64.StdEncoding.EncodeToString(helloSlc))}
    json, _ := json.Marshal(obj)
    fmt.Println(string(json))
}</code>

Output:

{"Content":"Hello"}

The above is the detailed content of How to Marshal a []byte Field as a String in Go JSON Encoding?. 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