Yaml 编解码器支持解码为map[string]any
并将此类映射编码为 yaml。
这个想法是解码文档和额外的树,然后将额外的映射放在所需的路径下,然后编码回来。
type YamlObject map[string]any
func main() {
// Parse the initial document
doc := make(YamlObject)
yaml.Unmarshal([]byte(document), &doc)
// Parse the additional nodes
addon := make(YamlObject)
yaml.Unmarshal([]byte(extra), &addon)
// Find the node by the path
node := findChild(doc, "spec", "mec", "customConfig", "sif")
if node == nil {
panic("Must not happen")
}
// Add the keys from the additional document
// under the specified path
for key, val := range addon {
(*node)[key] = val
}
// Output the modified document
outDoc, _ := yaml.Marshal(doc)
println(string(outDoc))
}
func findChild(obj YamlObject, path ...string) *YamlObject {
if len(path) == 0 {
return &obj
}
key := path[0]
child, ok := obj[key]
if !ok {
return nil
}
obj, ok = child.(YamlObject)
if !ok {
return nil
}
return findChild(obj, path[1:]...)
}
完整示例https://go.dev/play/p/pTdXR53p0mq https://go.dev/play/p/pTdXR53p0mq
Output:
spec:
mec:
customConfig:
sif:
prom_exporter:
type: prometheus_exporter
snk_dev:
buffer:
type: memory
compression: gzip
dken: ${SN}
encoding:
codec: json
ep: ${NT}
index: us
inputs:
- tesslt
type: sk_hc_logs
snk_prod:
buffer:
type: memory
compression: gzip
dken: ${SN}
encoding:
codec: json
ep: ${NT}
index: us
inputs:
- tesslt
type: sk_hc_logs
resources:
requests:
cpu: 100m
memory: 1Gi
tolerations:
- effect: NoSchedule
key: WorkGroup
operator: Equal
value: goxy
YAML 代码按字母顺序输出键