Skip to content

Instantly share code, notes, and snippets.

@jvz
Created July 1, 2017 18:16
Show Gist options
  • Save jvz/7db55698a77156c3ffca392e69532f82 to your computer and use it in GitHub Desktop.
Save jvz/7db55698a77156c3ffca392e69532f82 to your computer and use it in GitHub Desktop.
Example of using Scala Parser Combinators to parse JSON into an AST
import scala.util.parsing.combinator._
sealed trait Json
case object JsonNull extends Json
final case class JsonBoolean(b: Boolean) extends Json
final case class JsonString(s: String) extends Json
final case class JsonNumber(x: BigDecimal) extends Json
final case class JsonArray(elems: List[Json]) extends Json
final case class JsonObject(entries: List[(String, Json)]) extends Json
object Json extends JavaTokenParsers {
def value: Parser[Json] = (
obj
| arr
| stringLiteral ^^ JsonString
| floatingPointNumber ^^ (s => JsonNumber(BigDecimal(s)))
| "null" ^^ (_ => JsonNull)
| "true" ^^ (_ => JsonBoolean(true))
| "false" ^^ (_ => JsonBoolean(false))
)
def obj: Parser[JsonObject] = "{"~> repsep(member, ",") <~"}" ^^ JsonObject
def arr: Parser[JsonArray] = "["~> repsep(value, ",") <~"]" ^^ JsonArray
def member: Parser[(String, Json)] = stringLiteral~":"~value ^^ {
case k~":"~v => k -> v
}
def parseAll(in: CharSequence): ParseResult[Json] = parseAll(value, in)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment