Skip to content

Instantly share code, notes, and snippets.

@willyhorizont
Last active March 10, 2024 13:26
Show Gist options
  • Save willyhorizont/9a898597abaa332968b63ccdd1d0673a to your computer and use it in GitHub Desktop.
Save willyhorizont/9a898597abaa332968b63ccdd1d0673a to your computer and use it in GitHub Desktop.
Pretty Print | Pretty JSON Stringify in Swift
import Foundation
typealias MyObject = [String: Any?]
typealias MyArray = [Any?]
func prettyJsonStringify(_ anything: Any? = nil, indent: String = " ") -> String {
var indentLevel = 0
func prettyJsonStringifyInner(_ anythingInner: Any?, _ indentInner: String) -> String {
guard let anythingInner = anythingInner else {
return "null"
}
if let anythingInner = anythingInner as? String {
return "\"\(anythingInner)\""
}
if let anythingInner = anythingInner as? Bool {
return "\(anythingInner)"
}
if let anythingInner = anythingInner as? NSNumber {
return "\(anythingInner)"
}
if let anythingInner = anythingInner as? MyArray {
if (anythingInner.count == 0) {
return "[]"
}
indentLevel += 1
var result = "[\n\(String(repeating: indentInner, count: indentLevel))"
for (arrayItemIndex, arrayItem) in anythingInner.enumerated() {
result += prettyJsonStringifyInner(arrayItem, indentInner)
if ((arrayItemIndex + 1) != anythingInner.count) {
result += ",\n\(String(repeating: indentInner, count: indentLevel))"
}
}
indentLevel -= 1
result += "\n\(String(repeating: indentInner, count: indentLevel))]"
return result
}
if let anythingInner = anythingInner as? MyObject {
if (anythingInner.count == 0) {
return "{}"
}
indentLevel += 1
var result = "{\n\(String(repeating: indentInner, count: indentLevel))"
for (entryIndex, (objectKey, objectValue)) in anythingInner.enumerated() {
result += "\"\(objectKey)\": \(prettyJsonStringifyInner(objectValue, indentInner))"
if ((entryIndex + 1) != anythingInner.count) {
result += ",\n\(String(repeating: indentInner, count: indentLevel))"
}
}
indentLevel -= 1
result += "\n\(String(repeating: indentInner, count: indentLevel))}"
return result
}
return "null"
}
return prettyJsonStringifyInner(anything, indent)
}
let products: MyArray = [
[
"id": "P1",
"name": "bubble gum"
] as MyObject,
[
"id": "P2",
"name": "potato chips"
] as MyObject
]
print("products: \(prettyJsonStringify(products))")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment