我试图解组以下YAML(使用gopkg.in/yaml.v2)的:解组动态YAML映射结构
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)
什么是“动态YAML”?在[YAML规范](http://www.yaml.org/spec/1.2/spec.html)中没有提及“动态”。你指的是什么“顶级”?我会假设YAML代表的数据结构根部的映射,但该映射没有属性,因为它没有锚点,也没有标记。请**编辑**你的文章,以明确你所指的是什么。 – Anthon