将[]byte转换为JSON,得到一个奇怪的字符串。

huangapple go评论82阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2015年12月4日 21:43:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/34089750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定