go - 如何为[]byte的json.Marshal获取空列表[]而不是null?

标签 go slice

使用[]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类型将不起作用,因为 byteuint8 的别名所以[]uint8[]byte 相同和json.Marshal将输出""为此也是如此。

关于go - 如何为[]byte的json.Marshal获取空列表[]而不是null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73597936/

相关文章:

go - 如何在 Go 中将数组复制到另一个数组的一部分?

go - 如何在 golang 中实现 void*?

go - 如何解析 YAML 文件并从父结构创建子对象(继承)

python - 切片 Pandas Dataframe 时如何返回索引

go - 在 Go slice 中,为什么 s[lo :hi] end at element hi-1?

arrays - 为什么我的数组没有增长?

google-app-engine - 如何在 App Engine 模块之间共享文件(HTML 模板)?

go - gc如何处理slice内存回收

python - 从末尾开始迭代切片索引(python): how to avoid "-0" to be equal to "0"?

string - 有没有更好的方法来实现模仿有限字符显示的水平滚动文本效果?