Created
December 8, 2020 15:34
-
-
Save ipcjs/83a1b8048179182ba9cc5f5b148b834b to your computer and use it in GitHub Desktop.
convert json5 to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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