使用结构解析 YAML

4 yaml go

我创建了以下 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"
Run Code Online (Sandbox Code Playgroud)

https://codebeautify.org/yaml-validator/cbb349ec

我这里有:

  1. 一种环境(根)
  2. 环境包含 1..n sys
  3. 每个sys包含 1..n 个具有关键 app-type 的模型实例

现在我需要解析这个 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"`
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试解析这个 YAML,我得到一个索引超出范围的错误。

我的问题是:

1. Do I model the YAML correctly?
2. Do I model the struct correctly?
Run Code Online (Sandbox Code Playgroud)

这是代码:

func main() {
    y := Environments{}

    err := yaml.Unmarshal([]byte(data), &y)
    if err != nil {
        log.Fatalf("error: %v", err)
    }
    fmt.Printf("%+v\n", y)
}
Run Code Online (Sandbox Code Playgroud)

数据是yaml.file.

Daz*_*kin 8

尝试这个:

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)

}
Run Code Online (Sandbox Code Playgroud)