gpt4 book ai didi

parsing - 使用 viper 解析 YAML 时如何使用动态 key ?

转载 作者:数据小太阳 更新时间:2023-10-29 03:10:47 25 4
gpt4 key购买 nike

我有以下 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,但是如果我不知道字段名称(或者换句话说,如果它是动态的),我该怎么办?

最佳答案

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

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

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

在后一种情况下,items 片段的解码目标应该是一个映射——类似于

type Item struct {
Source string
Destination string
}

items := make(map[string]Item)

err := viper.Unmarshal(items)

关于parsing - 使用 viper 解析 YAML 时如何使用动态 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52230157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com