简体   繁体   中英

How to compare 2 maps and export the difference in Golang?

I have 2 yaml files that I've exported to 2 different map variables. My yaml files have this example of format:

file1.yaml

  a: b
  c: d
  e:
    - f
    - g
  x:
    - y

file2.yaml

  m: n
  c: d
  x:
    - y
    - z

I've unmarshalled the yaml files into structs. My goal is to now compare the 2 maps, and only output the difference found in file2.yaml . So far I have something simple:

type ParametersYaml struct {
    Parameters Params `yaml:"parameters""`
}

type Params map[string]interface{}

var pParam ParametersYaml
var sParam ParametersYaml

func Extractor(primaryYaml, secondaryYaml string) error {
    primaryOpenedFile, err := fileOpener(primaryYaml)
    secondaryOpenedFile, err := fileOpener(secondaryYaml)

    err = yamlParser(primaryOpenedFile, &pParam)
    err = yamlParser(secondaryOpenedFile, &sParam)

    if err != nil {
        return err
    }
    
    compare(pParam, sParam)

    return err

}

func fileOpener(file string) ([]byte, error) {
    f, err := ioutil.ReadFile(file)

    return f, err
}

func yamlParser(fileObject []byte, param *ParametersYaml) error {
    err := yaml.Unmarshal(fileObject, &param)
    return err
}

func compare(pMarshalled, sMarshalled ParametersYaml) {
    for s, sv := range sMarshalled.Parameters {
        for p, pv := range pMarshalled.Parameters {
            if s == p && sv == pv {
                break
            } else if s == p && sv != pv {
                fmt.Printf("%s: %s,\n", s, sv)
                break
            } else if _, ok := pMarshalled.Parameters[s]; !ok {
                fmt.Printf("%s: %s,\n", s, sv)
                break
            }
        }
    }
}

But it can't compare values with lists since the type is of interface{}.

There exists https://github.com/sters/yaml-diff which does the same thing you're intending to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM