I am definitely not getting this. Here is a given yaml file
items:
- item1:
one: "some"
two: "some string"
- item2:
one: "some"
two: "some string"
And a config:
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
}
I am using gopkg.in/yaml.v2
With this error:
Unmarshal: yaml: unmarshal errors:
line 6: cannot unmarshal !!seq into map[string]application.Item
Please help me understand what I am doing wrong here. I googled everywhere already. Thanks in advance.
First, you need to change your YAML to
items:
item1:
one: "some"
two: "some string"
item2:
one: "some"
two: "some string"
Then, in your go code
type Config struct {
Items map[string]Item
}
type Item struct {
One string
Two string
}
Then with
fmt.Printf("%+v\n", c.Items)
you will have
map[item1:{One:some Two:some string} item2:{One:some Two:some string}]
There are multiple problems with your mapping:
Item struct members are not exported. You have to export them:type Item struct {
One string `yaml:"one"`
Two string `yaml:"two"`
}
Items is an array of map of Itemstype conf struct {
Items []map[string]Item `yaml:"items"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With