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