首页 > 解决方案 > 如何将 yaml 解析/解组为数据结构

问题描述

我有以下 yaml,我想将其解析为 Go

env:
  production:
      asia:
          blue: config.prod-asia
      ph:
          blue: prod.ph.config.blue
          green: prod.phconfig.green
  staging:
      asia:
          blue: asia.config.blue
      ph:
          blue: phconfig.blue
          green: ph.config.green

但是我尝试了以下结构不起作用。

type env struct {
    Env map[string]region `yaml:"env"`
}

type region struct {
    Region map[string]config
}

type config map[string]string

我应该如何构建我的结构,以便我可以解析成如下的数据结构?

func main() {
    var d env

    source, err := ioutil.ReadFile("config.yaml")
    if err != nil {
        log.Fatal("Couldn't read yaml file.")
    }

    err = yaml.Unmarshal(source, &d)
    if err != nil {
        log.Fatal("Couldn't parse yaml file.")
    }

    fmt.Println(d)
}

上面运行时的输出是

# go run .
{map[production:{map[]} staging:{map[]}]}

使用的 yaml 库"gopkg.in/yaml.v2"

标签: goyaml

解决方案


type env struct {
    Env map[string]map[string]map[string]string `yaml:"env"`
}

用上面的例子解决了


推荐阅读