Reputation: 56
I have a simple yaml file with nested values, e.g.
name: pamela
favourites:
book: the-lion-the-witch-and-the-wardrobe
movie: barbie
I can successfully unmarshal that using the gopkg.in/yaml.v2
library into the following struct:
type Person struct {
Name string `yaml:"name"`
Favourites *Favourites `yaml:"favourites"`
}
type Favourites struct {
Book string `yaml:"book"`
Movie string `yaml:"movie"`
}
Is there a way to flatten the yaml where I don't want to create the struct favourites
but write the values of favourite book and movie to top level attributes.
So for example, the below does not work but is there anything like it that would allow me to read nested yaml values like this?
type Person struct {
Name string `yaml:"name"`
FavouriteBook `yaml:"favourites.book"`
FavouriteMovie `yaml:"favourites.movie"`
}
Caveat: I've seen the option of implementing a custom unmarshaller. I'd like to avoid that, so my question is more - does anyone know a yaml library that already supports this?
Upvotes: 0
Views: 378
Reputation: 39768
Embedding the Favourites
struct is a possibility:
type Person struct {
Favourites `yaml:"favourites"`
Name string `yaml:"name"`
}
type Favourites struct {
FavouriteBook string `yaml:"book"`
FavouriteMovie string `yaml:"movie"`
}
Then you can do person.FavouriteBook
etc.
Upvotes: 0
Reputation: 6058
With native Golang Unmarshal I don't believe you can do it without a custom Unmarshaller. That said, gson seems to offer that feature.
Upvotes: 0