Home > Backend Development > Golang > Why Does Go's `json.Marshal` Encode `[]byte` as a Base64 String?

Why Does Go's `json.Marshal` Encode `[]byte` as a Base64 String?

Patricia Arquette
Release: 2024-12-10 01:23:10
Original
325 people have browsed it

Why Does Go's `json.Marshal` Encode `[]byte` as a Base64 String?

Marshaling []byte to JSON

In Go, marshaling []byte to JSON differs slightly from other data types. Instead of directly encoding the bytes as an array, the JSON package encodes []byte as a base64-encoded string. This behavior is explicitly stated in the documentation for encoding/json:

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

Base64-Encoded String Output

In your case, the output of json.Marshal(group) contains "AAAAAQID". This represents the base64 encoding of your []byte slice:

originalBytes := []byte{0, 0, 0, 1, 2, 3}
encodedString := base64.StdEncoding.EncodeToString(originalBytes)

fmt.Println(encodedString) // Output: AAAAAQID
Copy after login

Decoding Base64 Data

To retrieve the original []byte values from the encoded string, you can decode the base64 data:

decodedBytes, err := base64.StdEncoding.DecodeString("AAAAAQID")
if err != nil {
    // Handle error
}

fmt.Println(decodedBytes) // Output: [0 0 0 1 2 3]
Copy after login

The above is the detailed content of Why Does Go's `json.Marshal` Encode `[]byte` as a Base64 String?. 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