Created
June 3, 2025 15:49
-
-
Save sneycampos/a78561baa7473562ae76c110d123b936 to your computer and use it in GitHub Desktop.
Flattens a map recursivelly in golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
func flattenMap(data map[string]any, prefix string, separator string) string { | |
var result []string | |
for key, value := range data { | |
newKey := key | |
if prefix != "" { | |
newKey = prefix + separator + key | |
} | |
switch v := value.(type) { | |
case map[string]any: | |
// If the value is a nested map, recursively flatten it | |
result = append(result, flattenMap(v, newKey, separator)) | |
default: | |
// If the value is not a map, append it to the result | |
result = append(result, fmt.Sprintf("%s: %v", newKey, value)) | |
} | |
} | |
return strings.Join(result, "\n") | |
} | |
func main() { | |
data := map[string]any{ | |
"user": map[string]any{ | |
"first_name": "silvio", | |
"age": 33, | |
"address": "Rua das Ruas Ruazadas, 22", | |
"family": map[string]any{ | |
"mother": map[string]any{ | |
"name": "Maria", | |
"age": 60, | |
}, | |
"father": map[string]any{ | |
"name": "João", | |
"age": 65, | |
"sons": []string{"Silvio", "Ana"}, | |
"parents": map[string]any{ | |
"grandmother": map[string]any{ | |
"name": "Ana", | |
"age": 85, | |
"address": "Rua das Avós, 456", | |
"phone": map[string]any{ | |
"home": "1234-5678", | |
"mobile": "9876-5432", | |
}, | |
}, | |
"grandfather": map[string]any{ | |
"name": "Carlos", | |
"age": 90, | |
"address": "Rua dos Avós, 123", | |
"phone": map[string]any{ | |
"home": "2345-6789", | |
"mobile": "8765-4321", | |
}, | |
}, | |
}, | |
}, | |
}, | |
}, | |
} | |
// Call the flattenMap function and print the result | |
result := flattenMap(data, "", "_") | |
fmt.Println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment