65 lines
2.2 KiB
Swift
65 lines
2.2 KiB
Swift
/// Pretty-prints JSON text with a 2-space indent.
|
|
///
|
|
/// It works on the text itself, not on a parsed value: a parse loses the key order and the
|
|
/// spelling of numbers (`1.50`, `1e3`).
|
|
public enum JSONFormatter {
|
|
public static func pretty(_ text: String) -> String {
|
|
let scalars = Array(text.unicodeScalars)
|
|
var out = String.UnicodeScalarView()
|
|
var depth = 0
|
|
func newline() {
|
|
out.append("\n")
|
|
out.append(contentsOf: String(repeating: " ", count: max(0, depth)).unicodeScalars)
|
|
}
|
|
var index = 0
|
|
while index < scalars.count {
|
|
let scalar = scalars[index]
|
|
switch scalar {
|
|
case "\"":
|
|
out.append(scalar)
|
|
index += 1
|
|
while index < scalars.count {
|
|
out.append(scalars[index])
|
|
if scalars[index] == "\\", index + 1 < scalars.count {
|
|
index += 1
|
|
out.append(scalars[index])
|
|
} else if scalars[index] == "\"" {
|
|
break
|
|
}
|
|
index += 1
|
|
}
|
|
case "{", "[":
|
|
let close: Unicode.Scalar = scalar == "{" ? "}" : "]"
|
|
var next = index + 1
|
|
while next < scalars.count, isSpace(scalars[next]) { next += 1 }
|
|
if next < scalars.count, scalars[next] == close {
|
|
out.append(scalar)
|
|
out.append(close)
|
|
index = next
|
|
} else {
|
|
out.append(scalar)
|
|
depth += 1
|
|
newline()
|
|
}
|
|
case "}", "]":
|
|
depth -= 1
|
|
newline()
|
|
out.append(scalar)
|
|
case ",":
|
|
out.append(scalar)
|
|
newline()
|
|
case ":":
|
|
out.append(contentsOf: ": ".unicodeScalars)
|
|
default:
|
|
if !isSpace(scalar) { out.append(scalar) }
|
|
}
|
|
index += 1
|
|
}
|
|
return String(out)
|
|
}
|
|
|
|
private static func isSpace(_ scalar: Unicode.Scalar) -> Bool {
|
|
scalar == " " || scalar == "\t" || scalar == "\n" || scalar == "\r"
|
|
}
|
|
}
|