将切片编组结果转换为字符字符串

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

Marshaling slice results in character string

问题

我正在尝试对一个 uint8 值的切片进行 JSON 编码,但结果是一个字符字符串。例如,这样做:

d := []uint8{1,2,3,4}
data, err := json.Marshal(d)
fmt.Println(string(data), err)

结果是:

"AQIDBA==" <nil>

我原本期望得到 [1,2,3,4],但实际上得到了这个奇怪的字符字符串。这里 是一个包含这段代码的 playground。

英文:

I'm trying to json encode a slice of uint8 values, but doing so results in a character string. As an example, this:

d := []uint8{1,2,3,4}
data, err := json.Marshal(d)
fmt.Println(string(data), err)

Results in:

&quot;AQIDBA==&quot; &lt;nil&gt;

I was expecting [1,2,3,4], but I am getting this odd character string instead. Here is a playground with this code on it.

答案1

得分: 4

这是因为你在数字中使用了uint8类型,而uint8byte的别名(规范:数值类型)。默认情况下,字节数组和切片使用Base64编码,这就是你看到的("AQIDBA=="是字节[1, 2, 3, 4]的Base64编码文本)。

引用自json.Marshal()文档:

> 数组和切片的值会被编码为JSON数组,除了[]byte会被编码为Base64编码的字符串,而nil切片会被编码为null的JSON对象。

将你的数字类型更改为uintint,然后你将看到你期望的结果。

例如(Go Playground):

type MyStruct struct {
	Data []uint
}

d := new(MyStruct)
d.Data = []uint{1, 2, 3, 4}

data, err := json.Marshal(d)
fmt.Println(string(data), err)

输出:

{"Data":[1,2,3,4]} <nil>
英文:

That's because you use uint8 type for your numbers, and uint8 is an alias for byte (Spec: Numeric types). And by default byte arrays and slices are encoded using Base64 encoding, that's what you see (&quot;AQIDBA==&quot; is the Base64 encoded text of the bytes [1, 2, 3, 4]).

Quoting from json.Marhsal() doc:

> 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.

Change your number type for uint or int for example, and then you will see what you expect.

For example (Go Playground):

type MyStruct struct {
	Data []uint
}

d := new(MyStruct)
d.Data = []uint{1, 2, 3, 4}

data, err := json.Marshal(d)
fmt.Println(string(data), err)

Output:

{&quot;Data&quot;:[1,2,3,4]} &lt;nil&gt;

huangapple
  • 本文由 发表于 2015年11月24日 16:24:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/33888625.html
匿名

发表评论

匿名网友

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

确定