【发布时间】:2018-03-26 17:37:28
【问题描述】:
我正在尝试解组以下 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)
【问题讨论】:
-
什么是“动态 YAML”? YAML specification 中没有提到“动态”。您指的是什么“顶级”?我假设映射位于 YAML 表示的数据结构的根部,但该映射没有属性,因为它没有锚点,也没有标签。请编辑您的帖子以明确您所指的内容。
标签: go yaml unmarshalling