Go to: Marshal [] bytes to JSON giving a strange string

When I try to marshal [] bytes in JSON format, I only get a strange string.

Check out the following code.

I have two doubts:

How can I output byte [] in JSON?

Why does [] 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) } 

output:

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

golang playground: https://play.golang.org/p/wanppBGzNR

+5
source share
1 answer

According to docs: https://golang.org/pkg/encoding/json/#Marshal

The array and slice values ​​are encoded as JSON arrays, except that [] bytes are encoded as a base64 encoded string, and the null fragment is encoded as a null JSON object.

The AAAAAQID value is a base64 representation of your byte fragment - for example,

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

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


All Articles