读取并合并两个Yaml文件 [英] Read and merge two Yaml files
问题描述
假设我们有两个Yaml文件
Assuming we have two yaml files
master.yaml
someProperty: "someVaue"
anotherProperty: "anotherValue"
override.yaml
someProperty: "overriddenVaue"
是否可以解组,合并然后将这些更改写入文件,而不必为yaml文件中的每个属性定义 struct
?
Is it possible to unmarshall, merge, and then write those changes to a file without having to define a struct
for every property in the yaml file?
主文件中有500多个属性,这些属性在执行时对服务而言根本不重要,因此理想情况下,我可以将其解编为地图,进行合并并再次用yaml写入但是我是相对较新的人,所以想提出一些意见.
The master file has over 500 properties in it that are not at all important to the service at this point of execution, so ideally I'd be able to just unmarshal into a map, do a merge and write out in yaml again but I'm relatively new to go so wanted some opinions.
我有一些代码可以将Yaml读入 interface
,但是我不确定将两者合并的最佳方法.
I've got some code to read the yaml into an interface
but i'm unsure on the best approach to then merge the two.
var masterYaml interface{}
yamlBytes, _ := ioutil.ReadFile("master.yaml")
yaml.Unmarshal(yamlBytes, &masterYaml)
var overrideYaml interface{}
yamlBytes, _ = ioutil.ReadFile("override.yaml")
yaml.Unmarshal(yamlBytes, &overrideYaml)
我已经研究过 mergo 这样的库,但是我不确定这是否是正确的方法
I've looked into libraries like mergo but i'm not sure if that's the right approach.
我希望在掌握母版之后,我可以写出具有属性的文件
I'm hoping that after the master I would be able to write out to file with properties
someProperty: "overriddenVaue"
anotherProperty: "anotherValue"
推荐答案
假设您只想在顶层进行合并,则可以将其编组为 map [string] interface {} 类型的地图,如下所示:
Assuming that you just want to merge at the top level, you can unmarshal into maps of type map[string]interface{}
, as follows:
软件包主要
import (
"io/ioutil"
"gopkg.in/yaml.v2"
)
func main() {
var master map[string]interface{}
bs, err := ioutil.ReadFile("master.yaml")
if err != nil {
panic(err)
}
if err := yaml.Unmarshal(bs, &master); err != nil {
panic(err)
}
var override map[string]interface{}
bs, err = ioutil.ReadFile("override.yaml")
if err != nil {
panic(err)
}
if err := yaml.Unmarshal(bs, &override); err != nil {
panic(err)
}
for k, v := range override {
master[k] = v
}
bs, err = yaml.Marshal(master)
if err != nil {
panic(err)
}
if err := ioutil.WriteFile("merged.yaml", bs, 0644); err != nil {
panic(err)
}
}
这篇关于读取并合并两个Yaml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!