Mark LeMoine
Mark LeMoine

Reputation: 4628

Preserving order of YAML maps using 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.

Upvotes: 11

Views: 7467

Answers (1)

Fandy Dharmawan
Fandy Dharmawan

Reputation: 328

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)

Upvotes: 12

Related Questions