Golang YAML Unmarshal无法解析嵌套YAML键问题
Go YAML解析嵌套属性失败的解决方法
我尝试从YAML文件加载一组对象,但嵌套的special_abilities属性始终无法被正确解析,结果为空切片。
相关代码与文件
用于Unmarshal的原结构体
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"` }
加载函数
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 }
待解析的characters.yaml文件
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"
输出结果(special_abilities为空)
&{[{Er Cipolla 5 10 2 []} {Fagiolino 2 2 3 []}]}
问题原因
使用匿名嵌套结构体时,Go的YAML解析库(如gopkg.in/yaml.v2/v3)在反射解析过程中无法正确识别嵌套结构的字段映射关系,导致嵌套属性解析失败。
解决方案
将嵌套的匿名结构体定义为命名类型,让解析库能明确识别结构映射。修改后的结构体如下:
type SpecialAbility struct { Name string `yaml:"name"` Description string `yaml:"description"` Effect string `yaml:"effect,omitempty"` } type Character struct { Name string `yaml:"name"` Cost int `yaml:"cost"` Health int `yaml:"health"` Attack int `yaml:"attack"` SpecialAbilities []SpecialAbility `yaml:"special_abilities"` } type Deck struct { Characters []Character `yaml:"characters"` }
修改后重新运行加载函数,special_abilities字段将被正确解析,输出会包含对应的嵌套属性内容。
内容的提问来源于stack exchange,提问作者simone staffoli
相关产品推荐
相关产品推荐

