在 Golang 中将 Toml 格式转换为 Json 格式

我有 toml 文件,需要转换为 Json,反之亦然,在 golang 包中它只有命令工具而不是函数。如果有人对如何在 Go 语言中将 toml 转换为 json 和反之亦然有准确的想法,那就太好了



千万里不及你
浏览 405回答 1
1回答

凤凰求蛊

我会使用一些流行的 toml 库将 toml 解析为结构,然后使用标准库将其编组为 JSON。下面的代码使用了https://github.com/BurntSushi/toml。请注意,为简洁起见,没有错误处理。type Config struct {    Age        int       `json:"age,omitempty"`    Cats       []string  `json:"cats,omitempty"`    Pi         float64   `json:"pi,omitempty"`    Perfection []int     `json:"perfection,omitempty"`    DOB        time.Time `json:"dob,omitempty"`}var tomlData = `Age = 25Cats = [ "Cauchy", "Plato" ]Pi = 3.14Perfection = [ 6, 28, 496, 8128 ]DOB = 1987-07-05T05:45:00Z`func main() {    var conf Config    toml.Decode(tomlData, &conf)    j, _ := json.MarshalIndent(conf, "", "  ")    fmt.Println(string(j))}输出:{  "age": 25,  "cats": [    "Cauchy",    "Plato"  ],  "pi": 3.14,  "perfection": [    6,    28,    496,    8128  ],  "dob": "1987-07-05T05:45:00Z"}https://play.golang.com/p/91JqFjkJIXI
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go