I am attempting to perform an XPath based extraction using Lift JSON except that the xpath pattern of extraction is determined during runtime
To illustrate, I'd like to convert string "a.b.c.d" to Lift JSON extraction using (json \ "a" \ "b" \ "c").extract[List[Int]]
import net.liftweb.json._
import net.liftweb.json.JsonDSL._
import net.liftweb.json.JsonAST._
import net.liftweb.json.Extraction._
implicit val formats = net.liftweb.json.DefaultFormats
val x = """{ "a" : { "b" : [ {"c" : 10},{ "c" : 20 } ] } }"""
val json = parse(x)
val dataString = "a.b.c"
val dataList = dataString.split("\\.").toList
// List(a,b,c)
// I'd want to convert the above string to - (json \ "a" \ "b" \ "c").extract[List[Int]]
Is it possible to use foldLeft to achieve this pattern?
If I understand your question, this is what you want:
List("a", "b", "c").foldLeft(json){ _ \ _ }.extract[List[Int]]
And to help understand why:
foldLeft
takes two arguments; an initial state, and a function that takes the "current" state and the next input, returning the "next" state. The "inputs" are the elements of the thing you're calling foldLeft
on, i.e. the List("a", "b", "c")
.
So if you use json
as your initial state, the first state change call will be json \ "a"
. The next will be the result of that calculation, backslash "b", and so on.