英文:
Converting Toml format to Json Format in Golang
问题
我有一个toml文件,需要将其转换为Json,反之亦然,在golang包中只有命令工具而不是函数。
如果有人对如何在Go语言中将toml转换为json以及反之有明确的想法,那就太好了。
英文:
I have toml file and that needs to be converted to Json and vice versa and in golang packages it has just command tools rather than functions.
It would be great if anyone has precise idea about how to convert toml to json and vice versa in Go language
答案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 = 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://play.golang.com/p/91JqFjkJIXI
英文:
I would just use some popular toml library to parse toml to a struct and then use the standard library to marhshal it to JSON.
The below code makes use of https://github.com/BurntSushi/toml.
Note, no error handling for brevity.
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))
}
Output:
{
"age": 25,
"cats": [
"Cauchy",
"Plato"
],
"pi": 3.14,
"perfection": [
6,
28,
496,
8128
],
"dob": "1987-07-05T05:45:00Z"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论