package main
import (
"log"
"strings"
yaml "gopkg.in/yaml.v3"
)
func main() {
var node yaml.Node
data := []byte(strings.TrimSpace(`
block1:
# the comment
map:
key1: a
key2: b
block2:
hi: there
`))
log.Printf("INPUT:\n %s", data)
if err := yaml.Unmarshal(data, &node); err != nil {
log.Fatalf("Unmarshalling failed %s", err)
}
results, err := yaml.Marshal(node.Content[0])
if err != nil {
log.Fatalf("Marshalling failed %s", err)
}
log.Printf("RESULT:\n %s", results)
}
输出
2009/11/10 23:00:00 INPUT:
block1:
# the comment
map:
key1: a
key2: b
block2:
hi: there
2009/11/10 23:00:00 RESULT:
block1:
# the comment
map:
key1: a
key2: b
block2:
hi: there
我也找过,目前只发现一个办法。像是 go-yaml 这个库提供了
yaml.Node
结构,Marshal
/Unmarshal
到这个结构可以保留注释信息。输出