我绝对不明白这一点。这是给定的Yaml文件
items:
- item1:
one: "some"
two: "some string"
- item2:
one: "some"
two: "some string"
和一个配置:
type Item struct {
one string
two string
}
type conf struct {
Items map[string]Item
}
func (c *conf) getConfig(filename string) *conf {
yamlFile, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}
err = yaml.Unmarshal(yamlFile, &c)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}
//c.Items = make(map[string]Items)
return c
}
我正在使用
gopkg.in/yaml.v2
出现此错误:
Unmarshal: yaml: unmarshal errors:
line 6: cannot unmarshal !!seq into map[string]application.Item
请帮助我了解我在这里做错了什么。我已经到处搜索了。
提前致谢。
最佳答案
首先,您需要将YAML更改为
items:
item1:
one: "some"
two: "some string"
item2:
one: "some"
two: "some string"
然后,在您的代码中
type Config struct {
Items map[string]Item
}
type Item struct {
One string
Two string
}
然后用
fmt.Printf("%+v\n", c.Items)
你将会有
map[item1:{One:some Two:some string} item2:{One:some Two:some string}]
关于go - YAML Unmarshal map [string] struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61943470/