1 回答
TA贡献1868条经验 获得超4个赞
如果您解组为: ,您可以使用go-yamlyaml.Node
执行此操作:
package main
import (
"os"
"gopkg.in/yaml.v3"
)
var input = []byte(`root:
entry1: val1`)
func main() {
var document yaml.Node
if err := yaml.Unmarshal(input, &document); err != nil {
panic(err)
}
data := document.Content[0]
var rootVal *yaml.Node
for i := 0; i < len(data.Content); i += 2 {
node := data.Content[i]
if node.Kind == yaml.ScalarNode && node.Value == "root" {
rootVal = data.Content[i+1]
break
}
}
if rootVal == nil {
panic("root key missing")
}
found := false
for i := 0; i < len(rootVal.Content); i += 2 {
node := rootVal.Content[i]
if node.Kind != yaml.ScalarNode {
continue
}
switch node.Value {
case "entry1":
rootVal.Content[i+1].SetString("valUpdated")
case "entry2":
found = true
}
}
if !found {
var key, value yaml.Node
key.SetString("entry2")
value.SetString("newkey added")
rootVal.Content = append(rootVal.Content, &key, &value)
}
out, err := yaml.Marshal(data)
if err != nil {
panic(err)
}
os.Stdout.Write(out)
}
输出:
root:
entry1: valUpdated
entry2: newkey added
Unmarshal获取一个以根节点作为唯一内容节点的文档节点。Marshal期望根节点作为数据,所以你输入data而不是document输入它。我不太确定为什么 API 是这样的。
- 1 回答
- 0 关注
- 147 浏览
添加回答
举报