英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论