doudi2833 2018-09-07 22:08
浏览 60

用毒蛇解析YAML时如何使用动态密钥?

I have the following yml file:

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

And I want to use viper to parse it, but name-of-item can be anything, so I'm not sure how to solve that. I know that I could use the following:

// 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)
    }
}

In this case, I can unmarshal because I'm declaring NameOfItem, but what should I do if I don't know the name of the field (or in other words, if it's dynamic)?

  • 写回答

1条回答 默认 最新

  • duanjing9339 2018-09-08 16:41
    关注

    The struct types in Go may not be dynamic (I doubt they may in any other strictly-typed language), so you have to use a two stage process:

    1. Unmarshal the relevant piece of data into a value of type map[string]interface{}.
    2. Post process the result by iterating over the map's keys and use type assertions for the values corresponding to particular keys.

    But it's not clear from your question whether your YAML data are really arbitrary or the items key contains a uniform array of items—I mean, each item consists of the source and destination values, just the keys for the items themselves are not known.

    In this latter case, the target for the unmarshaling of the items piece should be a map—something like

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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测