将动态YAML解组到结构图 [英] Unmarshal dynamic YAML to map of structs

查看:64
本文介绍了将动态YAML解组到结构图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解封以下YAML(使用gopkg.in/yaml.v2):

I'm trying to unmarshal the following YAML (using 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

顶级属性是动态的,因此我需要将它们解析为字符串,结构中的所有其他键将始终相同,因此这些部分的结构也是如此.我该如何解析?

The top level properties are dynamic so I need to parse them as string, every other key in the structure will always be the same, hence the structs for those parts. How can I parse this?

(完整代码位于 https://github.com/tirithen/unit-conversion/blob/master/convert.go#L84 )

推荐答案

问题是您的 m l 的内容不是 conversionGroup s,但包含 conversionGroup s的列表.

The problem is that the contents of your m and l aren't conversionGroups but lists of conversionGroups.

尝试一下:

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

,它应该解析.请注意 conversionGroup 之前的 [] .

and it should parse. Note the [] before conversionGroup.

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

Then the question is whether that's the structure you really want :)

这篇关于将动态YAML解组到结构图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆