duanchoupo1104 2018-10-01 06:00
浏览 1277

如何使用Viper从嵌套的YAML结构中获取值?

My question:

How do I write the code below to get a string from my nested yaml struct?

Here is my yaml:

    element:
      - one:
          url: http://test
          nested: 123
      - two:
          url: http://test
          nested: 123

    weather:
      - test:
          zipcode: 12345
      - ca:
          zipcode: 90210

Here is example code

    viper.SetConfigName("main_config")
      viper.AddConfigPath(".")
      err := viper.ReadInConfig()
      if err != nil {
        panic(err)
      }
    testvar := viper.GetString("element.one.url")

My problem:

I get a blank string when I print this. According to the docs, this is how you get a nested element. I suspect its not working because the elements are lists. Do I need to do a struct? I am new to go so not sure how to make one, especially if it needs to be nested.

  • 写回答

1条回答 默认 最新

  • dsiuz86842 2018-10-01 07:21
    关注

    There are different Get methods available in viper library and your YML structure is of type []map[string]string, so to parse your YML configuration file you have to use viper.Get method. So you have to parse your file something like this..

    Note: You can use struct as well to un-marshal the data. Please refer this post mapping-nested-config-yaml-to-struct

    package main
    
    import (
        "fmt"
    
        "github.com/spf13/viper"
    )
    
    func main() {
        viper.SetConfigName("config")
        viper.AddConfigPath(".")
        err := viper.ReadInConfig()
        if err != nil {
            panic(err)
        }
        testvar := viper.Get("element")
        fmt.Println(testvar)
        elementsMap := testvar.([]interface{})
        for k, vmap := range elementsMap {
            fmt.Print("Key: ", k) 
            fmt.Println(" Value: ", vmap)
            eachElementsMap := vmap.(map[interface{}]interface{})
    
            for k, vEachValMap := range eachElementsMap {
                fmt.Printf("%v: %v 
    ", k, vEachValMap)
                vEachValDataMap := vEachValMap.(map[interface{}]interface{})
    
                for k, v := range vEachValDataMap {
                    fmt.Printf("%v: %v 
    ", k, v)
                }
            }
        }
    }
    
    // Output:
    /*
    Key: 0 Value:  map[one:map[url:http://test nested:123]]
    one: map[url:http://test nested:123]
    url: http://test
    nested: 123
    Key: 1 Value:  map[two:map[url:http://test nested:123]]
    two: map[url:http://test nested:123]
    url: http://test
    nested: 123
    */
    
    评论

报告相同问题?

悬赏问题

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