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
Patricia ArquetteOriginal
2024-12-10 01:23:10337browse

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.

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

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]

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!

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