有没有办法将 yaml 节点添加到 golang 中现有的 yaml 文档?

我正在阅读带有 goyaml lib 的 yaml 文件。如果要添加的密钥不存在,我打算修改它的一些条目并添加一个条目。

例如

原始yaml

root:
  entry1: val1

1 个模组和 1 个添加目标 yaml

root:
 entry1: valUpdated
 entry2: newkey added

我找不到任何可以让我向 yaml 添加节点的 yaml 库。


动漫人物
浏览 148回答 1
1回答

MYYA

如果您解组为:&nbsp;,您可以使用go-yamlyaml.Node执行此操作:package mainimport (&nbsp; &nbsp; "os"&nbsp; &nbsp; "gopkg.in/yaml.v3")var input = []byte(`root:&nbsp; entry1: val1`)func main() {&nbsp; &nbsp; var document yaml.Node&nbsp; &nbsp; if err := yaml.Unmarshal(input, &document); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; data := document.Content[0]&nbsp; &nbsp; var rootVal *yaml.Node&nbsp; &nbsp; for i := 0; i < len(data.Content); i += 2 {&nbsp; &nbsp; &nbsp; &nbsp; node := data.Content[i]&nbsp; &nbsp; &nbsp; &nbsp; if node.Kind == yaml.ScalarNode && node.Value == "root" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rootVal = data.Content[i+1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if rootVal == nil {&nbsp; &nbsp; &nbsp; &nbsp; panic("root key missing")&nbsp; &nbsp; }&nbsp; &nbsp; found := false&nbsp; &nbsp; for i := 0; i < len(rootVal.Content); i += 2 {&nbsp; &nbsp; &nbsp; &nbsp; node := rootVal.Content[i]&nbsp; &nbsp; &nbsp; &nbsp; if node.Kind != yaml.ScalarNode {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; switch node.Value {&nbsp; &nbsp; &nbsp; &nbsp; case "entry1":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rootVal.Content[i+1].SetString("valUpdated")&nbsp; &nbsp; &nbsp; &nbsp; case "entry2":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; found = true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; if !found {&nbsp; &nbsp; &nbsp; &nbsp; var key, value yaml.Node&nbsp; &nbsp; &nbsp; &nbsp; key.SetString("entry2")&nbsp; &nbsp; &nbsp; &nbsp; value.SetString("newkey added")&nbsp; &nbsp; &nbsp; &nbsp; rootVal.Content = append(rootVal.Content, &key, &value)&nbsp; &nbsp; }&nbsp; &nbsp; out, err := yaml.Marshal(data)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; os.Stdout.Write(out)}输出:root:&nbsp; &nbsp; entry1: valUpdated&nbsp; &nbsp; entry2: newkey added游乐场链接Unmarshal获取一个以根节点作为唯一内容节点的文档节点。Marshal期望根节点作为数据,所以你输入data而不是document输入它。我不太确定为什么 API 是这样的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go