2018-08-21 11:39
浏览 699


Assuming we have two yaml files


someProperty: "someVaue"
anotherProperty: "anotherValue"


someProperty: "overriddenVaue"

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?

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.

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)

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"
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dqrqp8492 2018-08-21 11:49

    Assuming that you just want to merge at the top level, you can unmarshal into maps of type map[string]interface{}, as follows:

    package main

    import (
    func main() {
        var master map[string]interface{}
        bs, err := ioutil.ReadFile("master.yaml")
        if err != nil {
        if err := yaml.Unmarshal(bs, &master); err != nil {
        var override map[string]interface{}
        bs, err = ioutil.ReadFile("override.yaml")
        if err != nil {
        if err := yaml.Unmarshal(bs, &override); err != nil {
        for k, v := range override {
            master[k] = v
        bs, err = yaml.Marshal(master)
        if err != nil {
        if err := ioutil.WriteFile("merged.yaml", bs, 0644); err != nil {
    解决 无用
    打赏 举报

相关推荐 更多相似问题