我创建了以下 YAML 文件来提供用户需要提供的一些配置:
Environments:
sys1:
models:
- app-type: app1
service-type: “fds"
- app-type: app2
service-type: “era”
sys2:
models:
- app-type: app1
service-type: “fds"
- app-type: app2
service-type: “era"
https://codebeautify.org/yaml-validator/cbb349ec https://codebeautify.org/yaml-validator/cbb349ec
我这里有:
- 一个环境(根)
- 环境包含 1..n
sys
- Each
sys
包含 1..n 个具有关键应用程序类型的模型实例
现在我需要解析这个 YAML 文件,因此我尝试构建一个结构类型,例如:
type Environment struct {
Environment [] sys
}
type sys struct{
Models []Properties
}
type Models struct{
app-type string `yaml:"app-type"`
service-type string `yaml:"service-type"`
}
现在我尝试解析此 YAML,但收到索引超出范围的错误。
我的问题是:
1. Do I model the YAML correctly?
2. Do I model the struct correctly?
这是代码:
func main() {
y := Environments{}
err := yaml.Unmarshal([]byte(data), &y)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%+v\n", y)
}
数据是yaml.file
.
尝试这个:
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
type Message struct {
Environments map[string]models `yaml:"Environments"`
}
type models map[string][]Model
type Model struct {
AppType string `yaml:"app-type"`
ServiceType string `yaml:"service-type"`
}
func main() {
data := []byte(`
Environments:
sys1:
models:
- app-type: app1
service-type: fds
- app-type: app2
service-type: era
sys2:
models:
- app-type: app1
service-type: fds
- app-type: app2
service-type: era
`)
y := Message{}
err := yaml.Unmarshal([]byte(data), &y)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%+v\n", y)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)