How to load a list of maps with viper?
Asked Answered
S

1

5

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?

Sferics answered 15/7, 2017 at 17:27 Comment(0)
T
11

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}}}
Terricolous answered 15/7, 2017 at 18:10 Comment(1)
I guess it's time to take a break :-) ThanksSferics

© 2022 - 2024 — McMap. All rights reserved.