【问题标题】:How to load a list of maps with viper?如何使用 viper 加载地图列表?
【发布时间】:2017-07-15 17:27:01
【问题描述】:

我想用 viper 加载以下配置:

artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969

我不知道如何加载地图列表。我想我只需要解组这个键,但是这段代码不起作用:

type Album struct {
    Name string
    Year int
}

type Artist struct {
    Name string
    Albums []Album
}

var artist Artist
viper.UnmarshalKey("artists", &artist)

我错过了什么?

【问题讨论】:

    标签: go viper-go


    【解决方案1】:

    您确定 yaml 中的键是 artists 吗?你的意思是提供artist

    工作示例:

    str := []byte(`artist:
      name: The Beatles
      albums:
      - name: The White Album
        year: 1968
      - name: Abbey Road
        year: 1969
    `)
    
        viper.SetConfigType("yaml")
        viper.ReadConfig(bytes.NewBuffer(str))
    
        var artist Artist
        err := viper.UnmarshalKey("artist", &artist)
    
        fmt.Printf("%v, %#v\n", err, artist)
    

    输出:

    <nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}
    

    【讨论】:

    • 我想是时候休息一下了 :-) 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多