我正在尝试解码以下 YAML(使用 gopkg.in/yaml.v2):
m:
- unit: km
formula: magnitude / 1000
testFixtures:
- input: 1000
expected: 1
l:
- unit: ml
formula: magnitude * 1000
testFixtures:
- input: 1
expected: 1000
使用以下代码:
type ConversionTestFixture struct {
Input float64 `yaml:"input"`
Expected float64 `yaml:"expected"`
}
type conversionGroup struct {
Unit string `yaml:"unit"`
Formula string `yaml:"formula"`
TestFixtures []ConversionTestFixture `yaml:"testFixtures"`
}
conversionGroups := make(map[string]conversionGroup)
err = yaml.Unmarshal([]byte(raw), &conversionGroups)
if err != nil {
return
}
fmt.Println("conversionGroups", conversionGroups)
但它给了我以下错误:
Error: Received unexpected error:
yaml: unmarshal errors:
line 1: cannot unmarshal !!map into []map[string]main.conversionGroup
顶级属性是动态的,所以我需要将它们解析为字符串,结构中的每个其他键将始终相同,因此这些部分的结构。我该如何解析?
(完整代码在 https://github.com/tirithen/unit-conversion/blob/master/convert.go#L84 )
最佳答案
问题是您的 m
和 l
的内容不是 conversionGroup
而是 conversionGroup
的列表>s.
试试这个:
conversionGroups := make(map[string][]conversionGroup)
它应该解析。请注意 conversionGroup
之前的 []
。
那么问题是这是否是您真正想要的结构:)
关于go - 解码动态 YAML 以映射结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749302/