-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdo.go
70 lines (60 loc) · 1.83 KB
/
do.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package flatmap
import (
"fmt"
"reflect"
"strings"
)
/*
Do takes a nested map and flattens it into a single level map. The flattening
follows the [JSONPath] standard. Please see the example to understand how the
flattened output looks like.
[JSONPath]: https://datatracker.ietf.org/doc/html/rfc9535
*/
func Do(nested map[string]any) map[string]any {
flattened := map[string]any{}
for childKey, childValue := range nested {
rootKey := fmt.Sprintf("$.%s", childKey)
setChildren(flattened, rootKey, childValue)
}
return flattened
}
// setChildren is a helper function for flatten. It is invoked recursively on a
// child value. If the child is not a map or a slice, then the value is simply
// set on the flattened map. If the child is a map or a slice, then the
// function is invoked recursively on the child's values, until a
// non-map-non-slice value is hit.
func setChildren(flattened map[string]any, parentKey string, parentValue any) {
newKey := fmt.Sprintf(".%s", parentKey)
split := strings.Split(parentKey, "")
if len(split) > 1 {
firstTwo := strings.Join(split[0:2], "")
if firstTwo == "$." {
newKey = parentKey
}
}
if reflect.TypeOf(parentValue) == nil {
flattened[newKey] = parentValue
return
}
if reflect.TypeOf(parentValue).Kind() == reflect.Map {
children := parentValue.(map[string]any)
for childKey, childValue := range children {
newKey = fmt.Sprintf("%s.%s", parentKey, childKey)
setChildren(flattened, newKey, childValue)
}
return
}
if reflect.TypeOf(parentValue).Kind() == reflect.Slice {
children := parentValue.([]any)
if len(children) == 0 {
flattened[newKey] = children
return
}
for childIndex, childValue := range children {
newKey = fmt.Sprintf("%s[%v]", parentKey, childIndex)
setChildren(flattened, newKey, childValue)
}
return
}
flattened[newKey] = parentValue
}