我需要從結構值向 yaml 檔案添加條目config.Sif["snk_prod"] (我需要在運行時填充它)并嘗試以下操作,我嘗試了以下操作,但在填充結構時出現錯誤,知道嗎?
package main
import "gopkg.in/yaml.v3"
const document = `
spec:
mec:
customConfig:
sif:
prom_exporter:
type: prometheus_exporter
snk_dev:
type: sk_hc_logs
inputs:
- tesslt
ep: ${NT}
dken: ${SN}
`
type YamlObject map[string]any
type CustomConfig struct {
Sif map[string]interface{} `yaml:"sif,omitempty"`
}
type ecfg struct {
Type string `yaml:"type,omitempty"`
Inputs []string `yaml:"inputs,omitempty"`
Ep string `yaml:"ep,omitempty"`
Dken string `yaml:"dken,omitempty"`
}
func main() {
t := CustomConfig{}
config := &t
// -------I need to add it as struct values as I got the values on runtime dynamically
config.Sif["snk_prod"] = ecfg{
Type: "sk_hc_ls",
Inputs: []string{"tesslt"},
Ep: "${NT}",
}
yamlBytes, err := yaml.Marshal(t)
doc := make(YamlObject)
if err := yaml.Unmarshal([]byte(document), &doc); err != nil {
panic(err)
}
addon := make(YamlObject)
if err := yaml.Unmarshal(yamlBytes, &addon); err != nil {
panic(err)
}
node := findChild(doc, "spec", "mec", "customConfig", "sif")
if node == nil {
panic("Must not happen")
}
for key, val := range addon {
(*node)[key] = val
}
outDoc, err := yaml.Marshal(doc)
if err != nil {
panic(err)
}
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/6CHsOJPXqpw
搜索后我找到了這個答案https://stackoverflow.com/a/74089724/6340176 與我的非常相似,更改是我需要將其添加為結構值
最后我需要在下面添加新條目sif
最后輸出應如下所示
spec:
mec:
customConfig:
sif:
prom_exporter:
type: prometheus_exporter
snk_dev:
type: sk_hc_logs
inputs:
- tesslt
ep: ${NT}
dken: ${SN}
snk_prod:
type: sk_hc_ls
inputs:
- tesslt
ep: ${NT}
uj5u.com熱心網友回復:
替換創建yamlBytes如下:
t := make(map[string]interface{})
t["snk_prod"] = ecfg{
Type: "sk_hc_ls",
Inputs: []string{"tesslt"},
Ep: "${NT}",
}
yamlBytes, err := yaml.Marshal(t)
然后你會得到預期的結果。
順便說一句:因為您試圖將值插入未初始化的映射(config.Sifis nil),所以觸發了恐慌。例如,您可以在分配值之前使用以下代碼行簡單地創建一個空映射:
config.Sif = make(map[string]interface{})
但是代碼中會有一個額外的不需要的sif節點,例如這樣的:
...
sif:
prom_exporter:
type: prometheus_exporter
sif:
snk_prod:
...
因此,要動態添加的 yaml 片段應該如開頭所示生成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520347.html
標籤:json去yaml
