转到:将[] bytes封送至JSON,得到一个奇怪的字符串
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
当我尝试将[] byte编组为JSON格式时,我只有一个奇怪的字符串。 p> \ n
请查看以下代码。 p>
我有两个疑问: p>
如何将[] bytes编组为JSON?
为什么[] byte成为此字符串? p>
包main
import(
“ encoding / json”
“ fmt “
” os“
)
func main(){
type ColorGroup struct {
ByteSlice [] byte
SingleByte byte
IntSlice [] int
}
group:= ColorGroup {\ n ByteSlice:[] byte {0,0,0,1,2,3},
单字节:10,
IntSlice:[] int {0,0,0,1,2,3},
}
b,错误:= json.Marshal(组)
,如果错误!=无{
fmt.Println(“错误:”,错误)
}
os.Stdout.Write(b)
} \ n code> pre>
输出为: p>
{“ ByteSlice”:“ AAAAAQID”,“ SingleByte”:10,“ IntSlice“:[0,0,0,1,2,3]}
code> pre>
golang游乐场: http s://play.golang.org/p/wanppBGzNR p>
div>
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]