Created
July 26, 2022 03:47
-
-
Save mingyang91/06f4a489c313a16b9285dd375a565808 to your computer and use it in GitHub Desktop.
This code is totally electronic trash for solving an issue at V2EX, please don't use it in your production environment.
This file contains 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
// | |
object Vson extends RegexParsers: | |
val string: Parser[String] = """[^,:}]+""".r ^^ { str => str.trim } | |
val int: Parser[Int] = """-?\d+""".r ^^ (_.toInt) | |
val double: Parser[Double] = """-?\d+\.\d+""".r ^^ (_.toDouble) | |
val bool: Parser[Boolean] = "true" ^^^ true | "false" ^^^ false | |
def pair: Parser[(String, Json)] = (string <~ ":") ~ value ^^ { case k ~ v => (k, v) } | |
def obj: Parser[Json] = "{" ~> repsep(options | pair, ",") <~ "}" ^^ Json.fromFields | |
def tuple: Parser[(Int, String, String)] = ((int <~ ":") ~ string <~ ":") ~ string ^^ { case k ~ v1 ~ v2 => (k, v1, v2) } | |
def array: Parser[List[(Int, String, String)]] = repsep(tuple, ",") | |
def options: Vson.Parser[(String, Json)] = ("options" <~ ":") ~ array ^^ { case k ~ v => (k, v.asJson) } | |
def value: Parser[Json] = | |
string ^^ Json.fromString | |
| int ^^ Json.fromInt | |
| double ^^ Json.fromDoubleOrNull | |
| bool ^^ Json.fromBoolean | |
def run(text: String): Json = | |
parseAll(obj, text) match | |
case Success(json, _) => json | |
case Failure(msg, _) => throw new Exception(msg) | |
case Error(msg, _) => throw new Exception(msg) | |
object VsonTest extends App: | |
val res = Vson.run("{label :用户 id,searchType:1,hide:1,disabled:1,required:1,options:1:yes:tag-info,2:no:tag-danger}") | |
println(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result: