Go: marshal []byte to JSON, 给出一个奇怪的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34089750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:10:40  来源:igfitidea点击:

Go: marshal []byte to JSON, giving a strange string

jsongo

提问by someblue

When I try to marshal []byte to JSON format, I only got a strange string.

当我尝试将 []byte 编组为 JSON 格式时,我只得到一个奇怪的字符串。

Please look the following code.

请看下面的代码。

I have two doubt:

我有两个疑问:

How can I marshal []byte to JSON?

如何将 []byte 编组为 JSON?

Why []byte become this string?

为什么 []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)
}

the output is:

输出是:

{"ByteSlice":"AAAAAQID","SingleByte":10,"IntSlice":[0,0,0,1,2,3]}

golang playground: https://play.golang.org/p/wanppBGzNR

golang 游乐场:https: //play.golang.org/p/wanppBGzNR

回答by elithrar

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 数组,除了 []byte 编码为 base64 编码的字符串,而 nil 切片编码为 null JSON 对象。

The value AAAAAQIDis 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]