【问题标题】:Unmarshal dynamic YAML to map of structs将动态 YAML 解组为结构映射
【发布时间】: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


【解决方案1】:

问题是您的ml 的内容不是conversionGroups,而是conversionGroups 的列表。

试试这个:

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

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

那么问题是这是否是你真正想要的结构:)

【讨论】:

  • 感谢缺少方括号是它看起来的问题。 :) 现在它解析了,我想我认为 [string] 部分就足够了。
猜你喜欢
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 2018-07-30
相关资源
最近更新 更多