Using lift-json, is there an easy way to retrieve and move a list?

I think I can miss something fundamental from the xpath list-json architecture. The smoothest way I was able to extract and traverse the list is shown below. Can someone please show me the best technique:

class Example { @Test def traverseJsonArray() { def myOperation(kid:JObject) = println("kid="+kid) val json = JsonParser.parse(""" { "kids":[ {"name":"bob","age":3}, {"name":"angie","age":5}, ]} """) val list = ( json \\ "kids" ).children(0).children for ( kid <- list ) myOperation(kid.asInstanceOf[JObject]) } } 
+7
source share
1 answer

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 
+16
source

All Articles