Marshal []byte to JSON, giving a strange string [duplicate]

When I try to marshal []byte to JSON format, I only got a strange string.

Please look the following code.

I have two doubt:

How can I marshal []byte to JSON?

Why []byte become this string?

package main import ( "encoding/json" "fmt" "os" ) func main() { type ColorGroup struct { ByteSlice []byte SingleByte byte IntSlice []int } group := ColorGroup{ ByteSlice: []byte{0,0,0,1,2,3}, SingleByte: 10, IntSlice: []int{0,0,0,1,2,3}, } b, err := json.Marshal(group) if err != nil { fmt.Println("error:", err) } os.Stdout.Write(b) } 

the output is:

{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]} 

golang playground:

0

1 Answer

As per the docs:

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.

The value AAAAAQID is a base64 representation of your byte slice - e.g.

b, err := base64.StdEncoding.DecodeString("AAAAAQID") if err != nil { log.Fatal(err) } fmt.Printf("%v", b) // Outputs: [0 0 0 1 2 3] 

You Might Also Like