封送切片导致字符串

I'm trying to json encode a slice of uint8 values, but doing so results in a character string. As an example, this:

d := []uint8{1,2,3,4}
data, err := json.Marshal(d)
fmt.Println(string(data), err)

Results in:

"AQIDBA==" <nil>

I was expecting [1,2,3,4], but I am getting this odd character string instead. Here is a playground with this code on it.

That's because you use uint8 type for your numbers, and uint8 is an alias for byte (Spec: Numeric types). And by default byte arrays and slices are encoded using Base64 encoding, that's what you see ("AQIDBA==" is the Base64 encoded text of the bytes [1, 2, 3, 4]).

Quoting from json.Marhsal() doc:

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.

Change your number type for uint or int for example, and then you will see what you expect.

For example (Go Playground):

type MyStruct struct {
    Data []uint
}

d := new(MyStruct)
d.Data = []uint{1, 2, 3, 4}

data, err := json.Marshal(d)
fmt.Println(string(data), err)

Output:

{"Data":[1,2,3,4]} <nil>