英文:
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("yaml")
viper.ReadConfig(bytes.NewBuffer(str))
var artist Artist
err := viper.UnmarshalKey("artist", &artist)
fmt.Printf("%v, %#v\n", err, artist)
Output:
<nil>, main.Artist{Name:"The Beatles", Albums:[]main.Album{main.Album{Name:"The White Album", Year:1968}, main.Album{Name:"Abbey Road", Year:1969}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论