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

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

How to load a list of maps with viper?

问题

我有以下配置文件想要用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)

我漏掉了什么?

英文:

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

artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    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:

type Album struct {
	Name string
	Year int
}

type Artist struct {
    Name string
	Albums []Album
}

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

What am I missing?

答案1

得分: 9

你确定在 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}}}
英文:

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

Working example:

str := []byte(`artist:
  name: The Beatles
  albums:
  - name: The White Album
    year: 1968
  - name: Abbey Road
    year: 1969
`)

	viper.SetConfigType(&quot;yaml&quot;)
	viper.ReadConfig(bytes.NewBuffer(str))

	var artist Artist
	err := viper.UnmarshalKey(&quot;artist&quot;, &amp;artist)

	fmt.Printf(&quot;%v, %#v\n&quot;, err, artist)

Output:

&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:

确定