Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving order of YAML maps using Go

Tags:

yaml

go

I'm trying to figure out how to read a YAML file in Go, while preserving the order of keys as ordered in the YAML doc. Most of the examples I've seen involve sorting the keys, but that won't work in my case. In addition, the YAML is arbitrarily structured (keys are user-defined, and values are a mix of string and string lists, also user-defined), which complicates matters.

go-yaml.v2 seems to do what I want (http://blog.labix.org/2014/09/22/announcing-yaml-v2-for-go), but I can't find any examples on how to use the ordering functionality. That, along with being completely new to Go, is leaving me pretty stumped.

I'd be happy to provide examples of the YAML I'm trying to parse, if needed.

like image 567
Mark LeMoine Avatar asked Nov 10 '15 20:11

Mark LeMoine


1 Answers

Here you go:

var data = `
  a: Easy!
  b:
  c: 2
  d: [3, 4]
`
m := yaml.MapSlice{}
err := yaml.Unmarshal([]byte(data), &m)
if err != nil {
    log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
like image 56
Fandy Dharmawan Avatar answered Nov 17 '22 07:11

Fandy Dharmawan