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
    */
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮