Go unmarshal yaml and preserve order
Just found the answer right before I wanted to post the question.
The answer is MapSlice!
You need to import yaml.v2
from gopkg
. (As of writing this MapSlices don't seem to be implemented in yaml.v3 yet)
MapSlices
implement exactly what I needed and are made of a number of MapItem
s.
type MapItem struct {
Key, Value interface{}
}
So now just unmarshal to a MapSlice. If you want to work with your own types you can always convert it but might need to do some typecasting.
m := yaml.MapSlice{}
yaml.Unmarshal(yaml_file, &m)
t := []Element{}
for _, item := range m {
t = append(t, Element{item.Key.(string), item.Value})
}