我有toml文件,需要转换为Json,反之亦然,在golang包中,它只是命令工具,而不是函数。如果有人对如何把toml转换成json有准确的想法,那就太好了,Go语言反之亦然。
发布于 2022-01-19 08:55:06
我只需使用一些流行的toml库将toml解析为struct,然后使用标准库将其分解为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 = 25
Cats = [ "Cauchy", "Plato" ]
Pi = 3.14
Perfection = [ 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://stackoverflow.com/questions/70767601
复制相似问题