Skip to content

Instantly share code, notes, and snippets.

@Arneball Arneball/gist:6364058
Last active Dec 21, 2015

Embed
What would you like to do?
My json parser
object Parser {
def main(args: Array[String]): Unit = {
val shit = new JsonParser1()
println{
shit.parseAll(shit.something, """{"nagger": 3, "dicklen": 3.14e2, "slask": null, "arne": "sket", "gammelarray": ["arne", 3, true], "nested": {"apa": true}}""")
}
}
}
class JsonParser1 extends RegexParsers {
private val j_str = """"[^"]*"""".r ^^ { JsString(_) }
private val j_bool = "true" ^^ { _ => JsBoolean(true) } | "false" ^^ { _ => JsBoolean(false) }
private val j_null = "null" ^^ { _ => JsNull }
private val j_int = """(0|[1-9]\d*)""".r ^^ { i => JsNum(i.toInt) }
private val j_float = raw"[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?".r ^^ {str => JsNum(BigDecimal(str))}
private val j_num = j_float | j_int
private val j_array = "[" ~> repsep(something*, ",") <~ "]" ^^ { case the_array => JsArray(the_array.flatten: _*) }
private val j_obj = "{" ~> repsep(key_value*, ",") <~ "}" ^^ { case fields => JsObj(fields.flatten: _*) }
private val key_value: Parser[(JsString, JsVal)] = (j_str <~ ":") ~ something ^^ {
case key ~ value => key -> value
}
val something: Parser[JsVal] = j_str | j_num | j_bool | j_null | j_array | j_obj
}
trait JsVal{
def value: Any
override def toString = value.toString
}
case object JsNull extends JsVal{
def value = "null"
}
case class JsArray(value: JsVal*) extends JsVal{
override def toString = value.mkString("[", ",", "]")
}
case class JsBoolean(value: Boolean) extends JsVal
case class JsObj(value: (JsString, JsVal)*) extends JsVal{
override def toString = value.map{ case (key, value) => s"$key: $value"}.mkString("{", ",", "}")
}
case class JsString(value : String) extends JsVal
case class JsNum(value: BigDecimal) extends JsVal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.