-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_string_any.go
42 lines (36 loc) · 963 Bytes
/
map_string_any.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
package populate_struct
// Gol sets VAL in DATA at the path specified by PATH
func AddToMapStringAny(data map[string]any, path []string, val any) {
lastIndex := len(path) - 1
// Traverse the map and create intermediate maps if needed
current := data
for _, key := range path[:lastIndex] {
// If key doesn't exist or isn't a map, create a new map
if next, ok := current[key].(map[string]any); ok {
current = next
} else {
newMap := make(map[string]any)
current[key] = newMap
current = newMap
}
}
// Set the value at the final key in the path
finalKey := path[lastIndex]
current[finalKey] = val
}
func GetFromMapStringAny(m map[string]any, path []string) (any, error) {
var current any = m
for _, field := range path {
switch v := current.(type) {
case map[string]any:
var ok bool
current, ok = v[field]
if !ok {
return nil, FieldNotFound
}
default:
return nil, InvalidPath
}
}
return current, nil
}