小编典典

将动态YAML解组到结构图

go

我正在尝试解组以下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)


阅读 279

收藏
2020-07-02

共1个答案

小编典典

问题是您m和的内容l不是,conversionGroup而是的列表conversionGroup

试试这个:

conversionGroups := make(map[string][]conversionGroup)

它应该解析。注意[]之前conversionGroup

然后的问题是,这是否就是您真正想要的结构:)

2020-07-02