【问题标题】:How to unmarshal dynamic YAML to a map of string -> string -> struct in Go?如何在 Go 中将动态 YAML 解组为字符串 -> 字符串 -> 结构的映射?
【发布时间】:2020-10-24 07:39:58
【问题描述】:

我正在尝试解组以下代码中的 YAML 数据。我的结构定义有什么问题?应该如何匹配数据格式?

Playground

package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
)

var data = `
fruits:
  apple:
    comments:
    - good
    - sweet
    from: US 
  pear:
    comments:
    - nice
    from: Canada
veggies:
  potato:
    comments:
    - filling
    from: UK
`

type List struct {
    Category map[string]struct {
        Name map[string]struct {
            Comments []string `yaml:"comments"`
            From     string   `yaml:"from"`
        }
    }
}

func main() {
    var l List
    err := yaml.Unmarshal([]byte(data), &l)
    if err != nil {
        log.Fatalf("Unmarshal: %v", err)
    }
    fmt.Println(l)
}

上面的代码输出一个空映射{map[]}

解决方案:

根据已验证答案Playground修复游乐场

【问题讨论】:

    标签: go yaml unmarshalling


    【解决方案1】:

    我相信你有两个问题:

    首先,您的List 类型与您的数据不匹配。它期望某种形式:

    ---
    Category:
      XXX:
        Name:
           XXX:
               Comments: [ ... ]
               From: ...
    

    其中“XXX”是任意键。这显然不是你所拥有的。

    看起来你只是想要一张地图:

    type List map[string]map[string]struct{
        Comments []string
        From     string
    }
    

    其次,您必须将指向目标对象的指针传递给Unmarshal 函数:

        var l List
        err := yaml.Unmarshal([]byte(data), &l) // <-- note &l not l
    

    【讨论】:

    • 谢谢!既是为了帮助进入正确的阶段,也是为了在这个清晰的解释中!
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 2021-02-11
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多