ds34222 2017-10-14 21:02
浏览 361
已采纳

将动态YAML解组到结构图

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

With the following code:

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)

But it gives me the following error:

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?

(full code are at https://github.com/tirithen/unit-conversion/blob/master/convert.go#L84)

  • 写回答

1条回答 默认 最新

  • dsfgds4215 2017-10-14 22:56
    关注

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

    Try this:

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化