【问题标题】:How to use dynamic keys when parsing YAML with viper?使用 viper 解析 YAML 时如何使用动态密钥?
【发布时间】:2019-02-13 06:10:09
【问题描述】:

我有以下 yml 文件:

# config.yml
items:
  name-of-item: # dynamic field
    source: ...
    destination: ...

我想用 viper 来解析它,但是name-of-item 可以是任何东西,所以我不知道如何解决这个问题。我知道我可以使用以下内容:

// inside config folder
package config

type Items struct {
  NameOfItem NameOfItem
}

type NameOfItem struct {
  Source string
  Destination string
}

// inside main.go
package main

import (
    "github.com/spf13/viper"
    "log"
    "github.com/username/lib/config"
)

func main() {

    viper.SetConfigName("config.yml")
    viper.AddConfigPath(".")

    var configuration config.Item
    if err := viper.ReadInConfig(); err != nil {
        log.Fatalf("Error reading config file, %s", err)
    }

    err := viper.Unmarshal(&configuration)
    if err != nil {
        log.Fatalf("unable to decode into struct, %v", err)
    }
}

在这种情况下,我可以解组,因为我声明了 NameOfItem,但是如果我不知道字段的名称(或者换句话说,如果它是动态的)该怎么办?

【问题讨论】:

    标签: parsing go struct yaml viper-go


    【解决方案1】:

    Go 中的 struct 类型可能不是动态的(我怀疑它们可能在任何其他严格类型的语言中),因此您必须使用两阶段过程:

    1. 将相关数据解组为 map[string]interface{} 类型的值。
    2. 通过遍历地图的键对结果进行后处理 并对与特定键对应的值使用类型断言。

    但从您的问题中不清楚您的 YAML 数据是否真的是任意的,或者 items 键是否包含一个 uniform 项目数组——我的意思是,每个项目都由 source 和 @ 组成987654325@ 值,只是项目本身的键是未知的。

    在后一种情况下,解组items 片段的目标应该是一个地图——类似于

    type Item struct {
      Source string
      Destination string
    }
    
    items := make(map[string]Item)
    
    err := viper.Unmarshal(items)
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 2016-03-10
      • 2020-08-01
      • 1970-01-01
      • 2015-11-15
      • 2019-03-03
      • 2019-08-06
      相关资源
      最近更新 更多