doutu9810 2019-08-16 14:21 采纳率: 0%
浏览 1835

如何打开YAML文件,更改某些内容并将其保存回Go中?

I need to change some values in YAML file from Go code. In my case, I need to change values.yaml file from Helm chart. Since that file can change, I do not structure of the whole file in advance (for example developers added new YAML sections in it in various projects). I just know how section that I want to change looks like.

I understand there is YAML library in Go (https://github.com/go-yaml/yaml). It will not do the job, because it assumes I know in advance structure of the file that I need to change. All examples are something like: 1. create struct 2. unmarshal YAML to struct 3. change 4. marshal and save back

It is not working for me since I do not know exact format of file, hence I cannot do step 1, create struct.

This is part of YAML file I am trying to change:

image:
  repository: nginx
  tag: stable
  pullPolicy: IfNotPresent

I understand this can be done with help of interface{}, but I do not understand how. Assuming that I understand struct, marshal/unmarshal YAML files, can someone provide code that will: 1. Load YAML file that has at least 20 entries in it and is of unknown structure 2. Change only 1 entry (in my case I want to change tag number for image section) 3. Save it back.

Thanks a lot !

  • 写回答

1条回答 默认 最新

  • douxiong2001 2019-08-16 14:36
    关注

    Something like this should work:

    data, err := ioutil.ReadFile(file)
    var v interface{}
    err = yaml.Unmarshal(data, &v)
    img, ok := v.["image"].(map[interface{}]interface{})
    if ok {
       img["tag"] = "somevalue"
    }
    

    The yaml library I use unmarshals into map[interface{}]interface{}. You need to add the necessary error checking, type assertions, etc.

    When done, you can yaml.Marshal(v) and write the result.

    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况