Debian Codegraph @

pkg/transformers/helpers/flatten.go

raw symbols SCIP
1 package helpers
2
3 import (
4 "fmt"
5 "strconv"
6 )
7
8 func Flatten(in interface{}) map[string]string {
9 out := make(map[string]string)
10 initial := make([]byte, 0, 64) // We sacrifice some memory but avoid expanding the initial buffer since most keys are not 2-10 runes long
11 flattenRecursive(&initial, in, out)
12 return out
13 }
14
15 // flattenRecursive flattens a JSON object into a map where each parent array or object for a field is appended to the its new key
16 // For example { "a" : { "b" : "c" } } should become { "a.b" : "c" }
17 // it is assumed that the root call is made with a JSON object and not a raw value or array
18 //
19 // prefixAcc keeps the prefix so far in a slice buffer
20 func flattenRecursive(prefixAcc *[]byte, in any, out map[string]string) {
21 // Note: if prefixAcc is []byte instead of *[]byte, then the slice header is copied on each call
22 // there is a chance that the byte array might be moved due to a required resize
23 // and then the caller's slice will no longer point to the same array, hence keeping both in memory for some time
24 // Which is why we use a pointer in the recursion and all calls should operate on the same slice header
25 prefix := *prefixAcc
26
27 if in == nil {
28 out[string(prefix)] = ""
29 return
30 }
31
32 switch obj := in.(type) {
33 case map[string]any:
34 if len(prefix) > 0 {
35 prefix = append(prefix, '.')
36 }
37 for k, v := range obj {
38 prefix = append(prefix, []byte(k)...)
39 flattenRecursive(&prefix, v, out)
40 prefix = prefix[:len(prefix)-len(k)]
41 }
42 if len(prefix) > 0 { // Remove the "." that we added
43 prefix = prefix[:len(prefix)-1]
44 }
45 case []any:
46 prefix = append(prefix, '[')
47 for elemIndex := range obj {
48 s := strconv.Itoa(elemIndex)
49 prefix = append(prefix, []byte(s)...)
50 prefix = append(prefix, ']')
51 flattenRecursive(&prefix, obj[elemIndex], out)
52 prefix = prefix[:len(prefix)-len(s)-1] // Remove "index]"
53 }
54 prefix = prefix[:len(prefix)-1] // Remove the '['
55 case string:
56 out[string(prefix)] = obj
57 case int:
58 out[string(prefix)] = strconv.Itoa(obj)
59 case int64:
60 out[string(prefix)] = strconv.FormatInt(obj, 10)
61 case uint64:
62 out[string(prefix)] = strconv.FormatUint(obj, 10)
63 case bool:
64 out[string(prefix)] = strconv.FormatBool(obj)
65 default:
66 out[string(prefix)] = fmt.Sprint(obj)
67 }
68 }