英文:
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:
"AQIDBA==" <nil>
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
类型,而uint8
是byte
的别名(规范:数值类型)。默认情况下,字节数组和切片使用Base64编码,这就是你看到的("AQIDBA=="
是字节[1, 2, 3, 4]
的Base64编码文本)。
引用自json.Marshal()
文档:
> 数组和切片的值会被编码为JSON数组,除了[]byte
会被编码为Base64编码的字符串,而nil
切片会被编码为null的JSON对象。
将你的数字类型更改为uint
或int
,然后你将看到你期望的结果。
例如(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 ("AQIDBA=="
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:
{"Data":[1,2,3,4]} <nil>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论