Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 703
someblue Avatar asked Dec 04 '15 13:12

someblue


1 Answers

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] 
like image 132
elithrar Avatar answered Nov 03 '22 01:11

elithrar