【问题标题】:Remove property from yaml file从 yaml 文件中删除属性
【发布时间】:2018-07-21 20:06:10
【问题描述】:

我需要读取 yaml 文件并更改一些属性值并将其写回 FS。

文件内容是这样的

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"`

}

我需要从输出中省略 type 属性

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

问题是,我能读,我可以改变属性值但不能删除键(即type

我使用的代码

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)
}

现在我可以循环像

这样的属性了
obj := models.OBJ{}


for i, element := range obj.Mod {

//Here I was able to change property data

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

但不确定在写回 FS 时如何省略 type 的整个属性。

我使用这个操作系统: https://github.com/go-yaml/yaml/tree/v2

【问题讨论】:

  • 你是怎么解决这个问题的?
  • @aerokite - 有你的建议 :)

标签: go struct type-conversion


【解决方案1】:

你只需要添加这个:

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

现在,如果你这样做(如果你愿意,可以在循环内):

obj.Mod[0].Type = "" // set to nil value of string
byt, _ := yaml.Marshal(obj)

并将byt 写入文件,类型将被删除。

要点是任何具有omitempty 标签的结构字段,当使用yaml.Marshal 编组时,如果它是empty,它将省略(删除)该字段( aka 有 nil 值)。

official documentation 中的更多信息。

【讨论】:

    【解决方案2】:

    如果您想从整个 YAML 中省略 type,您可以将数据编组到不再存在 type 的对象中

    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 将被删除。

    另一种解决方案如果您不想使用多个对象。

    在类型中使用omitempty。所以当Type的值为""时,会被忽略

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

    然后这样做

    for i, _ := range obj.Mod {
        obj.Mod[i].Type = ""
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 2017-04-18
      • 2013-02-20
      • 1970-01-01
      • 2013-02-18
      • 2011-05-12
      • 1970-01-01
      相关资源
      最近更新 更多