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) {
case map[string]any:
flattenJSON(key, child, out)
case []any:
if len(child) == 0 {
out[key] = ""
@@ -28,23 +29,27 @@ func flattenJSON(prefix string, in map[string]any, out map[string]any) {
for i, item := range child {
subKey := fmt.Sprintf("%s.%d", key, i)
switch itemValue := item.(type) {
case map[string]any:
flattenJSON(subKey, itemValue, out)
case []any:
if obj, ok := item.(map[string]any); ok {
flattenJSON(subKey, obj, out)
} else if arr, ok := item.([]any); ok {
tempMap := make(map[string]any)
tempMap["array"] = itemValue
tempMap["array"] = arr
flattenJSON(subKey, tempMap, out)
default:
} else {
out[subKey] = fmt.Sprintf("%v", item)
}
}
}
default:
if child == nil {
out[key] = ""
} else {
out[key] = fmt.Sprintf("%v", child)
}
}
}
}
func flattenJSONFile(inputFile string, outputFile string) error {
in, err := os.Open(inputFile)