If possible, you should upgrade to Lift JSON 2.3-M1 (http://www.scala-tools.org/repo-releases/net/liftweb/lift-json_2.8.1/2.3-M1/). It contains two important improvements, and the other contains expressions of the path.
In 2.3, path expressions never return JFields; instead, JFields values โโare returned directly. After that, your example will look like this:
val list = (json \ "kids").children for ( kid <- list ) myOperation(kid.asInstanceOf[JObject])
Lift JSON provides several styles for parsing values โโfrom JSON: path expressions, query understanding, and class extracts. You can combine and contrast these styles and get the best results that we often do. For completeness, I will give you several variations of the above example to get a better intuition of these different styles.
// Collect all JObjects from 'kids' array and iterate val JArray(kids) = json \ "kids" kids collect { case kid: JObject => kid } foreach myOperation // Yield the JObjects from 'kids' array and iterate over yielded list (for ( kid@JObject (_) <- json \ "kids") yield kid) foreach myOperation // Extract the values of 'kids' array as JObjects implicit val formats = DefaultFormats (json \ "kids").extract[List[JObject]] foreach myOperation // Extract the values of 'kids' array as case classes case class Kid(name: String, age: Int) (json \ "kids").extract[List[Kid]] foreach println // Query the JSON with a query comprehension val ks = for { JArray(kids) <- json kid@JObject (_) <- kids } yield kid ks foreach myOperation
Joni
source share