【问题标题】:How to parse/unmarshall yaml into data structure如何将 yaml 解析/解组为数据结构
【发布时间】:2021-03-13 02:47:05
【问题描述】:

我有以下 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"

【问题讨论】:

  • 如果您的代码不起作用:错误告诉您什么?
  • 没有错误...只是输出没有显示全部@Volker
  • 你使用的是哪个 yaml 库?
  • @CoreyOgburn 见上文
  • Region map[string]config 表示您期望 yaml 密钥为 Region(或 region),但您的输入中不存在该密钥。

标签: go yaml


【解决方案1】:
type env struct {
    Env map[string]map[string]map[string]string `yaml:"env"`
}

用上面的例子解决了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2019-01-20
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多