perf: 优化 json5 输出格式

This commit is contained in:
lisonge 2023-12-30 22:53:21 +08:00
parent 787398210d
commit 2534e81827

View File

@ -62,23 +62,30 @@ fun convertJsonElementToJson5(element: JsonElement, indent: Int = 2): String {
} }
is JsonObject -> { is JsonObject -> {
// Handle JSON objects if (element.isEmpty()) {
val entries = element.entries.joinToString(",\n") { (key, value) -> "{}"
// If key is a valid identifier, no quotes are needed } else {
if (key.matches(json5IdentifierReg)) { val entries = element.entries.joinToString(",\n") { (key, value) ->
"$key: ${convertJsonElementToJson5(value, indent)}" // If key is a valid identifier, no quotes are needed
} else { if (key.matches(json5IdentifierReg)) {
"${escapeString(key)}: ${convertJsonElementToJson5(value, indent)}" "$key: ${convertJsonElementToJson5(value, indent)}"
} } else {
}.lineSequence().map { l -> spaces + l }.joinToString("\n") "${escapeString(key)}: ${convertJsonElementToJson5(value, indent)}"
"{\n$entries\n}" }
}.lineSequence().map { l -> spaces + l }.joinToString("\n")
"{\n$entries\n}"
}
} }
is JsonArray -> { is JsonArray -> {
val elements = if (element.isEmpty()) {
element.joinToString(",\n") { convertJsonElementToJson5(it, indent) } "[]"
.lineSequence().map { l -> spaces + l }.joinToString("\n") } else {
"[\n$elements\n]" val elements =
element.joinToString(",\n") { convertJsonElementToJson5(it, indent) }
.lineSequence().map { l -> spaces + l }.joinToString("\n")
"[\n$elements\n]"
}
} }
} }
} }