【问题标题】:Ignored YAML tag忽略 YAML 标记
【发布时间】:2021-12-25 16:03:13
【问题描述】:

我有 config.yml 文件:

vcenter:
  connection: https 
  hostname: vcenter.mydomain.lan
  username: readonlyauto@vsphere.local
  password: mypasspord
  port: 443

EsxiExcludeDatastores:
  - datastore1
  - datastore2

EsxiExcludeDatastores2:
  datastores:
    - datastore1
    - datastore2

我正在尝试用“gopkg.in/yaml.v2”解析它

我创建了结构:

type FileConfig struct {
    Vcenter struct {
        ConnectionType string `yaml:"connection"`
        Hostname string `yaml:"hostname"`
        Username string `yaml:"username"`
        Password string `yaml:"password"`
        Port int `yaml:"port"`
    } `yaml:"vcenter"`
    EsxiExcludeDatastores struct {
        Datastores []string `yaml:"EsxiExcludeDatastores"`
    }
    EsxiExcludeDatastores2 struct {
        Datastores []string `yaml:"datastores"`
    } `yaml:"EsxiExcludeDatastores2"`
}

var AppConfig FileConfig

解析后,我打印结果:

    fmt.Println("Num of EsxiExcludeDatastores.Datastores = ", len(AppConfig.EsxiExcludeDatastores.Datastores))
    fmt.Println("Num of EsxiExcludeDatastores2.Datastores = ", len(AppConfig.EsxiExcludeDatastores2.Datastores))


Num of EsxiExcludeDatastores.Datastores =  0
Num of EsxiExcludeDatastores2.Datastores =  2

你能帮我吗,我在 EsxiExcludeDatastores 结构中做错了什么?如您所见,使用 EsxiExcludeDatastores2 一切正常,但 EsxiExcludeDatastores 为空。

我尝试以不同的方式做到这一点,但没有结果......

【问题讨论】:

    标签: go parsing yaml


    【解决方案1】:

    你快到了。

    要将 yaml 结构标记“提升”到“父”字段,请添加:

    EsxiExcludeDatastores struct {
        Datastores []string `yaml:"EsxiExcludeDatastores"`
    } `yaml:",inline"`   // <- this
    

    https://play.golang.org/p/S7QxGaspTyN


    yaml.v2 文档中,使用inline 标志的结构标记执行以下操作:

    内联字段,必须是struct或map,导致其所有 要处理的字段或键,就好像它们是外部的一部分一样 结构。对于maps,key不能和其他的yaml key冲突 结构字段。

    【讨论】:

      猜你喜欢
      • 2014-01-23
      • 2017-07-25
      • 1970-01-01
      • 2012-11-21
      • 2021-02-27
      • 2011-03-17
      • 2018-08-28
      • 2015-02-03
      • 2017-02-01
      相关资源
      最近更新 更多