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?
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}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With