Home > Backend Development > Golang > 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
Release: 2024-11-07 03:29:02
Original
1043 people have browsed it

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

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

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

Output:

{"Content":"SGVsbG8="}
Copy after login

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

Output:

{"Content":"Hello"}
Copy after login

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!

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