Skip to content

Instantly share code, notes, and snippets.

@mingyang91
Created July 26, 2022 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mingyang91/06f4a489c313a16b9285dd375a565808 to your computer and use it in GitHub Desktop.
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.
//
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)
@mingyang91
Copy link
Author

Result:

/Users/.../.sdkman/candidates/java/22.1.0.r17-grl/bin/java ......
{
  "label" : "用户 id",
  "searchType" : "1",
  "hide" : "1",
  "disabled" : "1",
  "required" : "1",
  "options" : [
    [
      1,
      "yes",
      "tag-info"
    ],
    [
      2,
      "no",
      "tag-danger"
    ]
  ]
}

Process finished with exit code 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment