如何在 Go 中将动态 YAML 解组为字符串 -> 字符串 -> 结构的映射?

How to unmarshal dynamic YAML to a map of string -> string -> struct in Go?

我正在尝试解组在此代码下方找到的 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

我相信你有两个问题:

首先,您的 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