Skip to content

Instantly share code, notes, and snippets.

@propensive
Last active August 29, 2015 14:14
Show Gist options
  • Save propensive/1b5cf07aac568fb4b2c9 to your computer and use it in GitHub Desktop.
Save propensive/1b5cf07aac568fb4b2c9 to your computer and use it in GitHub Desktop.
Recursive extraction in Rapture JSON
// Rapture imports
import rapture.json._
import jsonBackends.jawn._
// Define our AST
class Op(val opName: String) extends AnyVal { override def toString = opName }
sealed trait ExprTree
case class Ident(name: String) extends ExprTree { override def toString = name }
case class Expr(left: ExprTree, op: Op, right: ExprTree) extends ExprTree { override def toString = s"$left $op $right" }
// No implicit extractor for `ExprTree`s exists, so we need to define it by composing existing extractors
implicit def extractor: Extractor[ExprTree, Json] = Json.extractor[Ident] orElse Json.extractor[Expr]
// Let's create a sample JSON value:
val j = json"""{"left":{"left":{"name":"alpha"},"op":"+","right":{"name":"beta"}},"op":"*","right":{"left":{"name":"gamma"},"op":"/","right":{"name":"delta"}}}"""
val exprTree = j.as[ExprTree]
// Yields exprTree: ExprTree = alpha + beta * gamma / delta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment