Skip to content

Instantly share code, notes, and snippets.

@ipcjs
Created December 8, 2020 15:34
Show Gist options
  • Save ipcjs/83a1b8048179182ba9cc5f5b148b834b to your computer and use it in GitHub Desktop.
Save ipcjs/83a1b8048179182ba9cc5f5b148b834b to your computer and use it in GitHub Desktop.
convert json5 to json
package com.jinhandz.v2code.utils.ktx
/**
* see [JSON5 | JSON for Humans](https://json5.org/)
* */
object Json5 {
private val REGEX_MULTI_COMMENT = Regex("""/\*.*?\*/""", RegexOption.DOT_MATCHES_ALL)
private val REGEX_SINGLE_COMMENT = Regex("""^(.*)//.*$""")
private val REGEX_COMMA = Regex(""",\s*([]}])""")
fun convertJson5ToJson(json5: String): String {
return removeComma(removeSingleComment(removeMultiComment(json5)))
}
private fun removeMultiComment(json5: String): String {
return json5.replace(REGEX_MULTI_COMMENT, "")
}
private fun removeSingleComment(json5: String): String {
return json5.lineSequence().map { it.replace(REGEX_SINGLE_COMMENT, "$1") }
.joinToString("\n")
}
private fun removeComma(json5: String): String {
return json5.replace(REGEX_COMMA, "$1")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment