我正在尝试解码以下代码中的 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 {map[]}
.解决方案:
根据经过验证的答案修复游乐场 Playground
最佳答案
我相信你有两个问题:
首先,您的List
类型与您的数据不匹配。它期望某种形式:
---
Category:
XXX:
Name:
XXX:
Comments: [ ... ]
From: ...
其中“XXX”是任意键。这显然不是你所拥有的。看起来你只想要一张 map :
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
关于go - 如何将动态 YAML 解码为 Go 中字符串 -> 字符串 -> 结构的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62717802/