英文:
How to define a map in TOML?
问题
如何在TOML中定义一个映射(map)?
例如,我想定义如下内容:
[FOO]
Usernames_Passwords='{"user1":"pass1","user2":"pass2"}'
然后在Go语言中将其转换为map[string]string类型。
英文:
How to define a map in TOML?
For example, I want to define something like:
[FOO]
Usernames_Passwords='{"user1":"pass1","user2":"pass2"}'
and then in go convert them to a map[string]string
答案1
得分: 10
你可以像这样拥有类似的映射:
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" }]
英文:
You can have maps like this:
name = { first = "Tom", last = "Preston-Werner" }
point = { x = 1, y = 2 }
See: https://github.com/toml-lang/toml#user-content-inline-table
In your case, it looks like you want a password table, or an array of maps. You can make it like this:
[[user_entry]]
name = "user1"
pass = "pass1"
[[user_entry]]
name = "user2"
pass = "pass2"
Or more concisely:
user_entry = [{ name = "user1", pass = "pass1" },
{ name = "user2", pass = "pass2" }]
答案2
得分: 6
这是使用 github.com/BurntSushi/toml 进行的操作(不支持 内联表):
d := `
[FOO.Usernames_Passwords]
a="foo"
b="bar"
`
var s struct {
FOO struct {
Usernames_Passwords map[string]string
}
}
_, err := toml.Decode(d, &s)
// 检查 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)
英文:
This works using github.com/BurntSushi/toml (does not support 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)
Using github.com/naoina/toml this works (using inline tables):
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论