go - 为什么 encoding/json 将 slice 编码为 base64?

标签 go

这个问题在这里已经有了答案:





How to marshal a byte/uint8 array as json array in Go?

(1 个回答)



Marshal []byte to JSON, giving a strange string [duplicate]

(1 个回答)


1年前关闭。




我正在为一个 Restful api 编写一个 SDK。它具有非常非常嵌套的结构。
例如对于一部分数据。

type FieldUint8Options struct {
    MinValue  uint8   `json:"min_value"`
    MaxValue  uint8   `json:"max_value"`
    Step      uint    `json:"step"`
    Operation string  `json:"operation"`
    ValueList []uint8 `json:"value_list"`
}

type TTLOption struct {
    Value       uint8               `json:"value"`
    FieldEngine []FieldUint8Options `json:"field_engine"`
}
当我编码 TTLOption 结构的初始化数据时,ValueList 字段转换 base64 数据。
代码:
jsonFile, err := os.Open("example.json")
if err != nil {
    fmt.Println(err)
    os.Exit(0)
}
    
byteValue, _ := ioutil.ReadAll(jsonFile)

var ttl TTLOption
if err := json.Unmarshal(byteValue, &ttl); err != nil {
    fmt.Println(err)
    os.Exit(0)
}

// I also wrote Custom UnmarshalJSON() interface for TTLOption and FieldUint8Options to handle nil slices.
data, _ := json.Marshal(ttl)
fmt.Println(string(data))
输出:
'ttl': {'value': 123, 'field_engine': [{'min_value': 123, 'max_value': 222, 'step': 1, 'operation': 'random', 'value_list': 'ZA=='}]}}
如您所见, value_list 是 base64 表示。为什么它会这样?
谢谢和最好的问候。

最佳答案

正如 json marshaler 文档所说:

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.

byteuint8 的别名.
您可以使用 uint出于编码目的,它将编码为 JSON 数组。

关于go - 为什么 encoding/json 将 slice 编码为 base64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63660702/

相关文章:

google-app-engine - Go 中的数据存储区读取策略设置

go - 如何在 Go 中使用反射将结构的 nil 指针设置为结构的零值?

php - 不同应用程序之间的安全请求

pointers - struct中的指针和值有什么区别?

go - protoc 从属于不同包的两个 proto 文件生成 golang 代码

algorithm - 在 Go 中按字母顺序查找等分的字符串/单词

go - 如何切换数据库连接并将其共享到 Golang 中的模型? (Revel + Gorm)

google-app-engine - google.golang.org/appengine/datastore 与 cloud.google.com/go/datastore

go - fmt.Scanf 在 Go 中无法正常工作

mysql - 如何连接docker与compose、mysql、golang