拿Scala的Parser写了个解析JSON二维数组的工具 2016-02-17 06:28:33 感叹Scala的语法解析器之强大,几行代码就可以搞定我的解析需求,可惜相比专门的JSON解析库(ObjectMapper,fastjson)性能还差很多,不确定是否和apply的处理有关,抽空在研究下。 ```scala package cn.zhaishidan.test import scala.util.parsing.combinator.syntactical._ import scala.util.parsing.input.CharArrayReader import scala.util.parsing.combinator.ImplicitConversions /** * Created by stan on 16/2/17. */ object JsonArrayParser extends StdTokenParsers with ImplicitConversions { type Tokens = scala.util.parsing.json.Lexer val lexical = new Tokens lexical.reserved ++= List("true", "false", "null") lexical.delimiters ++= List("[", "]", ",") def jsonStr = accept("string", { case lexical.StringLit(n) => n }) def jsonNum = accept("number", { case lexical.NumericLit(n) => n }) def jsonVal = jsonStr | jsonNum | "true" ^^^ "true" | "false" ^^^ "false" | "null" ^^^ null def jsonArr: Parser[List[String]] = "[" ~> repsep(jsonVal, ",") <~ "]" ^^ (list => list) def data: Parser[List[List[String]]] = "[" ~> repsep(jsonArr, ",") <~ "]" ^^ (list => list) def apply(s: String): List[List[String]] = { phrase(data)(new lexical.Scanner(s)) match { case Success(result, _) => result case _ => throw new Exception("Illegal JSON format") } } } ``` 使用: ``` val json = """[["1", false], ["true", 4.878], [null, "3"], ["4", null]]""" val data = JsonArrayParser(json) println(data) ``` 非特殊说明,均为原创,原创文章,未经允许谢绝转载。 原始链接:拿Scala的Parser写了个解析JSON二维数组的工具 赏 Prev Spark执行任务Locality Level总是为ANY的问题 Next 4K显示器入手指南