forked from cozy/cozy-stack
/
normalize.go
52 lines (48 loc) · 1.37 KB
/
normalize.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
package config
import "fmt"
// Normalize can be used on a config loaded from a Yaml file so that it can
// encoded as JSON. Go doesn't want to encode map[interface{}]interface{} to
// JSON, so we need to do some tricks to have a type that is accepted by Go.
func Normalize(input map[string]interface{}) map[string]interface{} {
normalized := make(map[string]interface{}, len(input))
for k, v := range input {
switch v := v.(type) {
case map[interface{}]interface{}:
normalized[k] = doNormalizeMap(v)
case []interface{}:
normalized[k] = doNormalizeSlice(v)
default:
normalized[k] = v
}
}
return normalized
}
func doNormalizeMap(input map[interface{}]interface{}) map[string]interface{} {
normalized := make(map[string]interface{}, len(input))
for k, v := range input {
key := fmt.Sprintf("%v", k)
switch v := v.(type) {
case map[interface{}]interface{}:
normalized[key] = doNormalizeMap(v)
case []interface{}:
normalized[key] = doNormalizeSlice(v)
default:
normalized[key] = v
}
}
return normalized
}
func doNormalizeSlice(input []interface{}) []interface{} {
normalized := make([]interface{}, len(input))
for i, v := range input {
switch v := v.(type) {
case map[interface{}]interface{}:
normalized[i] = doNormalizeMap(v)
case []interface{}:
normalized[i] = doNormalizeSlice(v)
default:
normalized[i] = v
}
}
return normalized
}