保留使用Go的YAML映射的顺序。

huangapple go评论106阅读模式
英文:

Preserving order of YAML maps using Go

问题

我正在尝试弄清楚如何在Go中读取一个YAML文件,并保持键的顺序与YAML文档中的顺序相同。我看到的大多数示例都涉及对键进行排序,但在我的情况下这样做不起作用。此外,YAML的结构是任意的(键是用户定义的,值是字符串和字符串列表的混合,也是用户定义的),这使得问题更加复杂。

go-yaml.v2似乎可以实现我想要的功能(http://blog.labix.org/2014/09/22/announcing-yaml-v2-for-go),但我找不到任何关于如何使用排序功能的示例。加上我对Go完全不熟悉,这让我感到非常困惑。

如果需要,我可以提供我尝试解析的YAML示例。

英文:

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.

答案1

得分: 12

这是你要翻译的内容:

这里是你要的

    var data = `
      a: Easy!
      b:
      c: 2
      d: [3, 4]
    `
    m := yaml.MapSlice{}
	err := yaml.Unmarshal([]byte(data), &m)
	if err != nil {
		log.Fatalf("错误:%v", err)
	}
	fmt.Printf("--- m:\n%v\n\n", m)
英文:

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)

huangapple
  • 本文由 发表于 2015年11月11日 04:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/33639269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定