forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.go
54 lines (45 loc) · 1.18 KB
/
translate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package config
import "strings"
// TranslateKeys recursively translates all keys from m in-place to their
// canonical form as defined in dict which maps an alias name to the canonical
// name. If m already has a value for the canonical name then that one is used
// and the value for the alias name is discarded. Alias names are matched
// case-insensitive.
//
// Example:
//
// m = TranslateKeys(m, map[string]string{"CamelCase": "snake_case"})
//
func TranslateKeys(v map[string]interface{}, dict map[string]string) {
ck(v, dict)
}
func ck(v interface{}, dict map[string]string) interface{} {
switch x := v.(type) {
case map[string]interface{}:
for k, v := range x {
canonKey := dict[strings.ToLower(k)]
// no canonical key? -> use this key
if canonKey == "" {
x[k] = ck(v, dict)
continue
}
// delete the alias
delete(x, k)
// if there is a value for the canonical key then keep it
if _, ok := x[canonKey]; ok {
continue
}
// otherwise translate to the canonical key
x[canonKey] = ck(v, dict)
}
return x
case []interface{}:
var a []interface{}
for _, xv := range x {
a = append(a, ck(xv, dict))
}
return a
default:
return v
}
}