Skip to content

Instantly share code, notes, and snippets.

@gonyykim
Last active October 26, 2023 12:02
Show Gist options
  • Save gonyykim/1764938ef1ced505cc2b4af6dc81edb9 to your computer and use it in GitHub Desktop.
Save gonyykim/1764938ef1ced505cc2b4af6dc81edb9 to your computer and use it in GitHub Desktop.
flattenJson.kt
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