英文:
Marshal []byte to JSON, giving a strange string
问题
当我尝试将[]byte转换为JSON格式时,我只得到了一个奇怪的字符串。
请看下面的代码。
我有两个疑问:
如何将[]byte转换为JSON?
为什么[]byte会变成这个字符串?
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)
}
输出结果为:
{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]}
Golang Playground链接:https://play.golang.org/p/wanppBGzNR
英文:
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
答案1
得分: 46
根据文档:https://golang.org/pkg/encoding/json/#Marshal
数组和切片的值会被编码为 JSON 数组,但 []byte 会被编码为 base64 编码的字符串,而空切片会被编码为 null JSON 对象。
值 AAAAAQID
是你的字节切片的 base64 表示形式 - 例如:
b, err := base64.StdEncoding.DecodeString("AAAAAQID")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", b)
// 输出:[0 0 0 1 2 3]
英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论