Does Golang Yaml Unmarshal Support accessing nested yaml through struct tags?

38 Views Asked by At

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?

1

There are 1 best solutions below

0
Jim Wright On

With native Golang Unmarshal I don't believe you can do it without a custom Unmarshaller. That said, gson seems to offer that feature.