| 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) |
| 11 |
flattenRecursive(&initial, in, out) |
| 12 |
return out |
| 13 |
} |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
func flattenRecursive(prefixAcc *[]byte, in any, out map[string]string) { |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 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 { |
| 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] |
| 53 |
} |
| 54 |
prefix = prefix[:len(prefix)-1] |
| 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 |
} |