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

huangapple go评论72阅读模式
英文:

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"
}

https://play.golang.com/p/91JqFjkJIXI

huangapple
  • 本文由 发表于 2022年1月19日 16:44:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/70767601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定