'Golang compare and update keys from two different map string interfaces
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
Solution 1:[1]
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]
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
