Last active
October 26, 2023 12:02
-
-
Save gonyykim/1764938ef1ced505cc2b4af6dc81edb9 to your computer and use it in GitHub Desktop.
flattenJson.kt
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
fun flattenJson(json: Map<String, Any>, parentKey: String = ""): Map<String, Any> { | |
val result = mutableMapOf<String, Any>() | |
for ((key, value) in json) { | |
val fullKey = if (parentKey.isEmpty()) key else "$parentKey.$key" | |
when (value) { | |
is Map<*, *> -> { | |
// If the value is another JSON object, recursively flatten it | |
val nestedMap = value as Map<String, Any> | |
result.putAll(flattenJson(nestedMap, fullKey)) | |
} | |
else -> { | |
// If the value is not another JSON object, add it to the result | |
result[fullKey] = value | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment