gpt4 book ai didi

go - 使用结构解析 YAML

转载 作者:数据小太阳 更新时间:2023-10-29 03:02:57 26 4
gpt4 key购买 nike

我创建了以下 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

我这里有:

  1. 一个环境(root)
  2. 环境包含 1..n sys
  3. 每个 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)

}

关于go - 使用结构解析 YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51775247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com