Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a list of maps with viper?

Tags:

go

viper-go

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?

like image 493
jbrown Avatar asked Jan 31 '23 00:01

jbrown


1 Answers

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}}}
like image 153
jeevatkm Avatar answered Feb 02 '23 09:02

jeevatkm