如何在TOML中定义地图?

时间:2016-12-20 12:52:46

标签: go toml

为什么TOML不支持定义地图?什么是在TOML中定义map [string]字符串的最简单方法?

我想定义类似的东西

[FOO]

Usernames_Passwords='{"user1":"pass1","user2":"pass2"}'

然后将它们转换为map [string] string

2 个答案:

答案 0 :(得分:2)

这可以使用github.com/BurntSushi/toml(不支持inline tables):

d := `
    [FOO.Usernames_Passwords]
    a="foo"
    b="bar"
    `
var s struct {
    FOO struct {
        Usernames_Passwords map[string]string
    }
}
_, err := toml.Decode(d, &s)
// check err!
fmt.Printf("%+v", s)

使用github.com/naoina/toml这可行(使用内联表):

d := `
    [FOO]
    Usernames_Passwords = { a = "foo" , b = "bar" }
    `
var s struct {
    FOO struct {
        Usernames_Passwords map[string]string
    }
}
err := toml.Unmarshal([]byte(d), &s)
if err != nil {
    panic(err)
}
fmt.Printf("%+v", s)

答案 1 :(得分:0)

你可以有这样的地图:

name = { first = "Tom", last = "Preston-Werner" }
point = { x = 1, y = 2 }

请参阅:https://github.com/toml-lang/toml#user-content-inline-table

在您的情况下,您看起来想要一个密码表或一组地图。你可以这样做:

[[user_entry]]
name = "user1"
pass = "pass1"

[[user_entry]]
name = "user2"
pass = "pass2"

或者更简洁:

user_entry = [{ name = "user1", pass = "pass1" },
              { name = "user2", pass = "pass2" }]