代码点读机 / Go / json.Marshal

json.Marshal Go · 包功能

把 Go 值编码成 JSON 格式的字节切片。

怎么用

b, err := json.Marshal(值)

小例子

package main
import (
    "encoding/json"
    "fmt"
)

func main() {
    b, _ := json.Marshal(map[string]int{"x": 1})
    fmt.Println(string(b))
}

运行结果

输出 {"x":1}

提醒:结构体字段首字母大写才会被导出到 JSON

官方文档:https://pkg.go.dev/encoding/json#Marshal

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Go全部词条