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!