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: https://play.golang.org/p/wanppBGzNR
As per the docs: https://golang.org/pkg/encoding/json/#Marshal
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With