如何使用viper加载地图列表?

huangapple go评论110阅读模式
英文:

How to load a list of maps with viper?

问题

我有以下配置文件想要用viper加载:

  1. artist:
  2. name: The Beatles
  3. albums:
  4. - name: The White Album
  5. year: 1968
  6. - name: Abbey Road
  7. year: 1969

我无法弄清楚如何加载一个映射列表。我猜我需要解组这个键,但是这段代码不起作用:

  1. type Album struct {
  2. Name string
  3. Year int
  4. }
  5. type Artist struct {
  6. Name string
  7. Albums []Album
  8. }
  9. var artist Artist
  10. viper.UnmarshalKey("artists", &artist)

我漏掉了什么?

英文:

I have the following config I want to load with viper:

  1. artist:
  2. name: The Beatles
  3. albums:
  4. - name: The White Album
  5. year: 1968
  6. - name: Abbey Road
  7. year: 1969

I can't work out how to load a list of maps. I guess I need to unmarshal just this key, but this code doesn't work:

  1. type Album struct {
  2. Name string
  3. Year int
  4. }
  5. type Artist struct {
  6. Name string
  7. Albums []Album
  8. }
  9. var artist Artist
  10. viper.UnmarshalKey("artists", &artist)

What am I missing?

答案1

得分: 9

你确定在 yaml 中键是 artists 吗?你是不是想提供 artist

工作示例:

  1. str := []byte(`artist:
  2. name: The Beatles
  3. albums:
  4. - name: The White Album
  5. year: 1968
  6. - name: Abbey Road
  7. year: 1969
  8. `)
  9. viper.SetConfigType("yaml")
  10. viper.ReadConfig(bytes.NewBuffer(str))
  11. var artist Artist
  12. err := viper.UnmarshalKey("artist", &artist)
  13. fmt.Printf("%v, %#v\n", err, artist)

输出:

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

Are you sure key is artists in the yaml? Do you mean to supply artist?

Working example:

  1. str := []byte(`artist:
  2. name: The Beatles
  3. albums:
  4. - name: The White Album
  5. year: 1968
  6. - name: Abbey Road
  7. year: 1969
  8. `)
  9. viper.SetConfigType(&quot;yaml&quot;)
  10. viper.ReadConfig(bytes.NewBuffer(str))
  11. var artist Artist
  12. err := viper.UnmarshalKey(&quot;artist&quot;, &amp;artist)
  13. fmt.Printf(&quot;%v, %#v\n&quot;, err, artist)

Output:

  1. &lt;nil&gt;, main.Artist{Name:&quot;The Beatles&quot;, Albums:[]main.Album{main.Album{Name:&quot;The White Album&quot;, Year:1968}, main.Album{Name:&quot;Abbey Road&quot;, Year:1969}}}

huangapple
  • 本文由 发表于 2017年7月16日 01:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/45120927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定