Golang使用结构解析YAML

时间:2018-08-09 20:24:38

标签: go yaml

我创建了以下yams文件,以提供用户需要提供的一些配置

FirstOrDefault()

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

我在这里

  
      
  1. 1个环境(根)

  2.   
  3. 环境包含1..n sys

  4.   
  5. 系统包含具有关键应用程序类型的1..n模型实例

  6.   

现在我需要解析此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"

现在,我尝试解析此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"`
}

这是代码

1. Does I model the yaml correctly?
2. Does I model the struct correctly ? 

数据是yaml.file

1 个答案:

答案 0 :(得分:1)

尝试一下:

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)

}