flatten json

Signed-off-by: Hadi <112569860+anotherhadi@users.noreply.github.com>
This commit is contained in:
Hadi
2025-09-28 00:52:01 +02:00
parent fb90fcb125
commit c5e0ee0819

View File

@@ -21,6 +21,7 @@ func flattenJSON(prefix string, in map[string]any, out map[string]any) {
switch child := v.(type) { switch child := v.(type) {
case map[string]any: case map[string]any:
flattenJSON(key, child, out) flattenJSON(key, child, out)
case []any: case []any:
if len(child) == 0 { if len(child) == 0 {
out[key] = "" out[key] = ""
@@ -28,20 +29,24 @@ func flattenJSON(prefix string, in map[string]any, out map[string]any) {
for i, item := range child { for i, item := range child {
subKey := fmt.Sprintf("%s.%d", key, i) subKey := fmt.Sprintf("%s.%d", key, i)
switch itemValue := item.(type) { if obj, ok := item.(map[string]any); ok {
case map[string]any: flattenJSON(subKey, obj, out)
flattenJSON(subKey, itemValue, out) } else if arr, ok := item.([]any); ok {
case []any:
tempMap := make(map[string]any) tempMap := make(map[string]any)
tempMap["array"] = itemValue tempMap["array"] = arr
flattenJSON(subKey, tempMap, out) flattenJSON(subKey, tempMap, out)
default: } else {
out[subKey] = fmt.Sprintf("%v", item) out[subKey] = fmt.Sprintf("%v", item)
} }
} }
} }
default: default:
out[key] = fmt.Sprintf("%v", child) if child == nil {
out[key] = ""
} else {
out[key] = fmt.Sprintf("%v", child)
}
} }
} }
} }