Marshall slice leads to character string

I am trying json to encode a slice of values uint8, but this produces a character string. As an example:

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

Results in:

"AQIDBA==" <nil>

I expected [1,2,3,4], but instead get this odd character string. Here is a playground with this code on it.

+3
source share
1 answer

, uint8, uint8 - byte (Spec: ). - Base64, , ("AQIDBA==" - Base64 [1, 2, 3, 4]).

json.Marhsal() doc:

JSON, , [] base64, JSON.

uint int, , .

(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)

:

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

Source: https://habr.com/ru/post/1617195/


All Articles