【发布时间】:2021-09-28 15:29:42
【问题描述】:
我有一个 yaml 文件,目前写成:
host: hostname
resource:
File:
title: "file"
containment_path:
- Test
- Test::Value
tags:
- file
failed: false
skipped: false
corrective_change: false
Exec:
title: Exec
containment_path:
- Test
- Value::Test
tags:
- exec
failed: true
skipped: false
corrective_change: false
那么像 File 和 Exec 这样的资源中的值每次都可以不同
我使用这个结构来解析我的 YAML 数据
type YamlResource struct {
Host string `yaml:"host"`
Resource []Resource `yaml:"resource"`
}
type Resource struct {
ContainmentPath string `yaml:"containment_path"`
Skipped bool `yaml:"skipped"`
Failed bool `yaml:"failed"`
}
func ScanningYAMLModulesStatus(filename string) (YamlModulesStatus, error) {
f, err := os.Open(filename)
if err != nil {
fmt.Println("Error reading YAML ", filename, ": ", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
isRecord := false
data := ""
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(scanner.Text(), "host:") {
data += line + "\n"
}
if strings.Contains(scanner.Text(), "resource:") {
isRecord = true
}
if strings.Contains(scanner.Text(), "corrective_change:") {
break
}
if isRecord {
data += line + "\n"
}
}
if err := scanner.Err(); err != nil {
fmt.Println("Error scanning YAML ", filename, ": ", err)
}
var ConfigResource YamlResource
if err = yaml.Unmarshal([]byte(data), &ConfigResource); err != nil {
fmt.Println("Error parsing YAML ", filename, ": ", err)
}
return ConfigResource, err
}
我收到此错误,我想按块解析资源,因为我有很多数据,例如 File 块、Exec 块,并且我无法修改我的 YAML 文件
我使用包“gopkg.in/yaml.v2”
line 3: cannot unmarshal !!map into []main.YamlResource
如何在 Go 中执行此操作,以解析 File、Exec 和其他?
谢谢
【问题讨论】:
-
yaml 和结构定义不匹配恕我直言。阅读 yaml
Resource应该类似于type Resource struct { File File ; Exec Exec;}或map[string]interface{} -
您使用哪个库进行 yaml 编组?
-
@ShaileshSuryawanshi 我使用“gopkg.in/yaml.v2”进行 yaml 编组