【问题标题】:How do I read this YAML?我如何阅读这个 YAML?
【发布时间】:2020-12-16 02:31:39
【问题描述】:

我有一个如下所示的 YAML 配置文件

development: true
databases:
  - label: masterdata
    properties:
      host: localhost
      port: 54321
      user: admin
      password: nimda
      dialect: postgres
      dbname: business
  - label: transactional
    properties:
      host: localhost
      port: 54321
      user: webuser
      password: insecure
      dialect: postgres
      dbname: web

结构如下图

type ApplicationConfiguration struct {
    development bool         `yaml:"development"`
    databases   []Properties `yaml:"databases"`
}

type Properties struct {
    Label  string            `yaml:"label"`
    Values map[string]string `yaml:"properties"`
}

使用库gopkg.in/yaml.v2

尝试阅读本文

config := ApplicationConfiguration{}
b, _ := ioutil.ReadFile(configPath)
marshalError := yaml.Unmarshal(b, &config)

config 中的数据库值始终为 nil,而 development 始终为 false,这意味着它根本没有被解组。如何阅读此配置,可能是我使用了错误的结构或 yaml 需要更改或不同的 API?

【问题讨论】:

  • 这是因为 developmentdatabases 是私有的。 yaml 包只能看到公共字段。

标签: go yaml


【解决方案1】:

尝试使用以下结构解组它:

type ApplicationConfiguration struct {
Development bool `yaml:"development"`
Databases   []struct {
    Label      string `yaml:"label"`
    Properties struct {
        Host     string `yaml:"host"`
        Port     int    `yaml:"port"`
        User     string `yaml:"user"`
        Password string `yaml:"password"`
        Dialect  string `yaml:"dialect"`
        Dbname   string `yaml:"dbname"`
    } `yaml:"properties"`
} `yaml:"databases"`

如果您需要将道具解组到地图中,请尝试以下操作:

  1. 使用地图[字符串]接口{} 类型属性结构{ 标签字符串yaml:"label" 值映射[字符串]接口{} yaml:"properties" }

将其编组为结构,然后使用以下示例:

type databases interface{}

 var myMap map[string]interface{}
  1. 使用结构并在之后处理它:

    if v.Kind() == reflect.Map {
    for _, key := range v.MapKeys() {
        strct := v.MapIndex(key)
        fmt.Println(key.Interface(), strct.Interface())
    }}
    

【讨论】:

  • 只是改变 type ApplicationConfiguration struct { Development bool yaml:"development" Databases []Properties yaml:"databases" } type Properties struct { Label string yaml:"label" Values map[string]string yaml:"properties" } Works跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-20
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多