为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
千万里不及你 2022-10-24 17:04:58
我有 toml 文件,需要转换为 Json,反之亦然,在 golang 包中它只有命令工具而不是函数。如果有人对如何在 Go 语言中将 toml 转换为 json 和反之亦然有准确的想法,那就太好了
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

我会使用一些流行的 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


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 238 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信