score:0

Accepted answer

This should work:

  def nextLens = 'rec / element(0)

  @scala.annotation.tailrec
  final def getLens(json: JsObject, lensAcc: Lens[Id] = nextLens, depth: Int = 0): Lens[Id] = {
    if (depth > 10) {
      throw new IllegalStateException("Recursive search for lens exhausted.")
    }
    json.extract[JsObject](lensAcc / 'properties.?) match {
      case None => getLens(json, lensAcc / nextLens, depth + 1)
      case _ => lensAcc
    }
  }

Test:

scala> val json = JsonParser("""{"rec": [{"rec": [{"properties": {}}]}]}""").asJsObject
json: spray.json.JsObject = {"rec":[{"rec":[{"properties":{}}]}]}
scala> getLens(json)
res6: spray.json.lenses.Lens[spray.json.lenses.Id] = spray.json.lenses.JsonLenses$$anon$1@448cd79c
scala> json.extract[JsObject](res6)
res9: spray.json.JsObject = {"properties":{}}

I don't know if there is something like an empty lens...


Related Query

More Query from same tag