When I try to marshal []byte to JSON format, I only got a strange string.
当我尝试将[]字节编组为JSON格式时,我只得到一个奇怪的字符串。
Please look the following code.
请查看以下代码。
I have two doubt:
我有两个疑问:
How can I marshal []byte to JSON?
如何将[]字节编组为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
golang playground:https://play.golang.org/p/wanppBGzNR
1 个解决方案
#1
15
As per the docs: https://golang.org/pkg/encoding/json/#Marshal
根据文档: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.
数组和切片值编码为JSON数组,除了[]字节编码为base64编码的字符串,nil切片编码为空JSON对象。
The value AAAAAQID
is a base64 representation of your byte slice - e.g.
值AAAAAQID是字节切片的base64表示 - 例如
b, err := base64.StdEncoding.DecodeString("AAAAAQID")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", b)
// Outputs: [0 0 0 1 2 3]
#1
15
As per the docs: https://golang.org/pkg/encoding/json/#Marshal
根据文档: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.
数组和切片值编码为JSON数组,除了[]字节编码为base64编码的字符串,nil切片编码为空JSON对象。
The value AAAAAQID
is a base64 representation of your byte slice - e.g.
值AAAAAQID是字节切片的base64表示 - 例如
b, err := base64.StdEncoding.DecodeString("AAAAAQID")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", b)
// Outputs: [0 0 0 1 2 3]