Golang compare and update keys from two different map string interfaces

825 views Asked by At

After unmarshalling two yaml files to two different maps, i wanted to compare keys (both outer and inner keys as it is a nested map) of both maps and if any key (outer or inner key) is present in first map 'configMap' and absent in second map 'userconfigMap', i wanted to append that key in second map in proper location. Tried iterating over the maps like this but not able to proceed with the implementation as im a newbie to golang.

for k, v := range configMap {
        for k1, v1 := range userconfigMap {
            if configMap[k] = userconfigMap[k1] {
                if configMap[k].(map[string]interface{})[v] = 
                userconfigMap[k1].(map[string]interface{})[v1] {

                }
                else {
                    userconfigMap[k1].append(v)
                }
            }
        }
    }

sample yaml files configMap yaml file:

config:
    test1: "test1"
    test2: "test2"
http_port: 30008
https_port: 32223

userconfigMap yaml file:

config:
    test1: "test1"
http_port: 30008
https_port: 32223

Im using map string interface for unmarshalling

1

There are 1 answers

7
Fenistil On

You can check if a map key exist in go with _, found := map[key], and add the key to the second map if not:

for k1 := range configMap {
    if _, found := userconfigMap[k1]; !found {
        userconfigMap[k1] = configMap[k1]
    }
    if v, ok := configMap[k1].(map[string]interface{}); ok {
        if _, ok := userconfigMap[k1].(map[string]interface{}); !ok {
            log.Fatal("userconfigMap[" + k1 + "] is not a map[string]interface{}")
        }
        for k2 := range v {
            if _, found := userconfigMap[k1].(map[string]interface{})[k2]; !found {
                userconfigMap[k1].(map[string]interface{})[k2] = v[k2]
            }
        }
    }
}