I'd like to load a list of objects from a yaml file but for some reason the nested properties in my yaml file are not properly loaded:
This is the struct I'm trying to Unmarshal to:
type Deck struct {
Characters []struct {
Name string `yaml:"name"`
Cost int `yaml:"cost"`
Health int `yaml:"health"`
Attack int `yaml:"attack"`
SpecialAbilities []struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Effect string `yaml:"effect,omitempty"`
} `yaml:"special_abilities"`
} `yaml:"characters"`
}
This is my loading function:
func LoadDeck() *Deck {
yamlFile, err := os.ReadFile("characters.yaml")
if err != nil {
log.Println(err)
}
deck := &Deck{}
err = yaml.Unmarshal(yamlFile, deck)
if err != nil {
log.Println(err)
}
return deck
}
This is the characters.yaml file I'm trying to unmarshal:
characters:
- name: "Er Cipolla"
cost: 5
health: 10
attack: 2
special_abilities:
- name: "Battelcry"
description: "Makes everybody cry, it inflicts 1 damage"
effect: "Something happens"
- name: "Shield"
description: "This minion shields the others"
- name: "Fagiolino"
cost: 2
health: 2
attack: 3
special_abilities:
- name: "Shield"
description: "This minion shields the others"
effect: "Something happens"
This is the output, as you can see the special_abilities are empty:
&{[{Er Cipolla 5 10 2 []} {Fagiolino 2 2 3 []}]}
Maybe its because the package you are using. I'm using
require gopkg.in/yaml.v2 v2.4.0
and it works.