duanjia8215 2018-08-21 11:39
浏览 748
已采纳

读取并合并两个Yaml文件

Assuming we have two yaml files

master.yaml

someProperty: "someVaue"
anotherProperty: "anotherValue"

override.yaml

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 (
        "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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line