Skip to content

Instantly share code, notes, and snippets.

@willyhorizont
Last active March 10, 2024 13:27
Show Gist options
  • Save willyhorizont/beb837eb5a74ff95641ccaff8d9e7af5 to your computer and use it in GitHub Desktop.
Save willyhorizont/beb837eb5a74ff95641ccaff8d9e7af5 to your computer and use it in GitHub Desktop.
Pretty Print | Pretty JSON Stringify in Kotlin
fun main() {
fun prettyJsonStringify(anything: Any? = null, indent: String = " "): String {
var indentLevel = 0
fun prettyJsonStringifyInner(anythingInner: Any?, indentInner: String): String {
if (anythingInner == null) return "null"
if (anythingInner is String) return "\"${anythingInner}\""
if (anythingInner is Number || anythingInner is Boolean) return "${anythingInner}"
if (anythingInner is MutableList<*>) {
if (anythingInner.size == 0) return "[]"
indentLevel += 1
var result = "[\n${indentInner.repeat(indentLevel)}"
for ((arrayItemIndex, arrayItem) in anythingInner.withIndex()) {
result += prettyJsonStringifyInner(arrayItem, indentInner)
if ((arrayItemIndex + 1) != anythingInner.size) result += ",\n${indentInner.repeat(indentLevel)}"
}
indentLevel -= 1
result += "\n${indentInner.repeat(indentLevel)}]"
return result
}
if (anythingInner is MutableMap<*, *>) {
if (anythingInner.entries.size == 0) return "{}"
indentLevel += 1
var result = "{\n${indentInner.repeat(indentLevel)}"
anythingInner.entries.forEachIndexed { entryIndex, entryItem ->
val objectKey = entryItem.key
val objectValue = entryItem.value
result += "\"${objectKey}\": ${prettyJsonStringifyInner(objectValue, indentInner)}"
if ((entryIndex + 1) != anythingInner.entries.size) result += ",\n${indentInner.repeat(indentLevel)}"
}
indentLevel -= 1
result += "\n${indentInner.repeat(indentLevel)}}"
return result
}
return "null"
}
return prettyJsonStringifyInner(anything, indent)
}
val products = mutableListOf<Any?>(
mutableMapOf<String, Any?>(
"id" to "P1",
"name" to "bubble gum"
),
mutableMapOf<String, Any?>(
"id" to "P2",
"name" to "potato chips"
),
)
println("products: ${prettyJsonStringify(products)}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment