doujinge9648 2018-02-11 15:34
浏览 188
已采纳

从Yaml文件中删除属性

I need to read yaml file and change some properties value and write it back to the FS.

The file content is like this

ID: mytest
mod:
- name: user
  type: dev
  parameters:
    size: 256M
  build:
    builder: mybuild


type OBJ struct {
    Id            string      `yaml:"ID"`
    Mod           []*Mod   `yaml:"mod,omitempty"`
}


type Mod struct {
    Name       string
    Type       string
    Parameters       Parameters `yaml:"parameters,omitempty"`
    Build            Parameters `yaml:"build,omitempty"`

}

I need to omit the type property from the output

ID: mytest
mod:
- name: user
  parameters:
    size: 256M
  build:
    builder: mybuild

The problem is that, I can read it, I can change the property value but can not delete the key (which is type)

The code I use

yamlFile, err := ioutil.ReadFile("test.yaml")

//Here I parse the file to the model I’ve which is working fine
err := yaml.Unmarshal([]byte(yamlFile), &obj)
if err != nil {
    log.Printf("Yaml file is not valid, Error: " + err.Error())
    os.Exit(-1)
}

Now I was able to loop on the properties like

obj := models.OBJ{}


for i, element := range obj.Mod {

//Here I was able to change property data

mta.Mod[i].Name = "test123"

But not sure how I can omit the whole property of type when writing back to the FS.

I use this OS: https://github.com/go-yaml/yaml/tree/v2

  • 写回答

2条回答 默认 最新

  • dongyulian5801 2018-02-11 17:25
    关注

    If you want to omit type from your whole YAML, you can Marshal your data into an object where type is not more exists

    type OBJ struct {
        Id  string `yaml:"ID"`
        Mod []*Mod `yaml:"mod,omitempty"`
    }
    
    type Mod struct {
        Name        string
        //Type      string `yaml:"type"`
        Parameters  Parameters `yaml:"parameters,omitempty"`
        Build       Parameters `yaml:"build,omitempty"`
    }
    

    type will be removed, if you Marshal your data into this object.

    Another solution if you do not want to use multiple object.

    Use omitempty in Type. So when value of Type is "", it will be ignored

    type Mod struct {
        Name       string
        Type       string `yaml:"type,omitempty"`
        Parameters  Parameters `yaml:"parameters,omitempty"`
        Build       Parameters `yaml:"build,omitempty"`
    }
    

    And do this

    for i, _ := range obj.Mod {
        obj.Mod[i].Type = ""
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用