Home > Blockchain >  Parsing Only Certain Keys in a YAML File in Golang
Parsing Only Certain Keys in a YAML File in Golang

Time:09-22

I have a YAML file that I am reading in in Golang and unmarshaling to a struct. The file contains several keys, but I only need certain ones. What I am finding is that if I place the keys that aren't needed for this application at the bottom of the YAML file, everything works as expected, but if the keys are in random order, the unmarshaling / parsing returns unexpected values. For example:

Sample Simple YAML file:

---
  cat_name: rusty
  dog_name: billy
  cat_food: Purina
  dog_food: Blue
  cat_rescued: true
  dog_rescued: false
  cat_age: 4
  dog_age: 6
  happy: true
type MyStruct struct {
    Happy  bool  `yaml:"happy"`
    CatName  string  `yaml:"cat_name"`
    CatAge  int  `yaml:"cat_age"`
}

Code that does the unmarshaling:

data, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, fmt.Errorf("Could not read file %s. An error has occurred: %w", filename, err)
    }

    params := MyStruct{}
    if err = yaml.Unmarshal(data, &params); err != nil {
        return nil, fmt.Errorf("could not parse yaml from file. %w", err)
    }

    return &params, nil

What I am finding is that, I will get back the correct CatName, but that the other two fields (Happy and CatAge) will be false and 0, respectively.

However, if I change the ordering of the keys in the yaml file so that the three keys that I need for MyStruct are the top three in the YAML file, I will get back the expected data of true and 4.

I am pretty new to Golang and am wondering, after doing a lot of searching and experimentation, what I am missing? I am using the https://github.com/goccy/go-yaml library to do the unmarshaling. Is it expected when unmarshaling YAML to a struct that the order of the keys in the YAML file are in the same order as the struct fields? Thanks in advance.

CodePudding user response:

What I am finding is that, I will get back the correct CatName, but that the other two fields (Happy and CatAge) will be false and 0, respectively.

No, the above assumption is incorrect. Per the definitions and code you have, all the required fields should be updated as expected and the ordering of keys in the YAML or struct fields has no relevance on the final un-marshalled output.

See an example with go-yaml library at Go playground

  • Related