使用[]string{}
处理字符串时很容易获得空列表:
import (
"encoding/json"
"fmt"
)
func main() {
slice1 := []string{} // non-nil but zero-length
json1, _ := json.Marshal(slice1)
fmt.Printf("%s\n", json1) // []
}
上面代码的输出是[]
,但是当我使用[]byte
甚至使用[]byte{ }
返回""
。我应该如何获得像 []string{}
中那样的空列表?
import (
"encoding/json"
"fmt"
)
func main() {
slice2 := []byte{}
json2, _ := json.Marshal(slice2)
fmt.Printf("%s\n", json2) // ""
}
最佳答案
请参阅docs :
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 value.
粗体部分是为什么你会得到 ""
。如果你想要[]
来自[]byte{}
,您需要一个名为 []byte
的自定义实现 json.Marshaler
的类型界面。
或者,如果您正在寻找“整数 slice ”,请使用 []N
哪里N
可以是任何基本整数类型,但不能是 uint8
类型。 uint8
类型将不起作用,因为 byte
是 uint8
的别名所以[]uint8
与 []byte
相同和json.Marshal
将输出""
为此也是如此。
关于go - 如何为[]byte的json.Marshal获取空列表[]而不是null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73597936/