4

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?

jbrown
  • 7,518
  • 16
  • 69
  • 117

1 Answers1

9

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}}}
jeevatkm
  • 4,571
  • 1
  • 23
  • 24