Question

This is probably an easy one and my difficulty is likely caused by my newness to Scala (which already is fast becoming my favourite language).

Basically I have some JSON that looks like this:

{
"to"      : "Peter",
"from"    : "Dave",
"bundle"  : [
             {"data": [1,2,3,4,5]},
             {"data": [2,3,4,5,6]}
            ]

}

Now, I've parsed this JSON to the point where I can pull the data from the header (to and from) and can look over the individual messages in the bundle. At the moment I'm using this:

val messages = parsedJSON \\ "bundle" \\ classOf[JObject]

for (m <- messages) println(m)

Which gives me:

Map(data -> List(1, 2, 3, 4, 5))
Map(data -> List(2, 3, 4, 5, 6))

But what I want to do in that loop is take each Map and convert it back to JSON i.e.:

{
"data": [1,2,3,4,5]
}

I've tried render(m) and various other semi-random things to try and get it to work but so far no dice. The closest I've come gives me this error:

No implicit view available from Any => net.liftweb.json.package.JValue.

Can anyone please point me in the right direction?

Thanks in advance!

Was it helpful?

Solution

I think the easiest way to handle this is to create a case class for a bundle. Lift-json can then nicely extract the data into instances. Then you can just loop through them and turn them back into JObjects implicitly by creating 2-tuples.

case class Bundle(data: List[BigInt])

val bundles = (parsedJSON \\ "bundle").extract[List[Bundle]]
// List(Bundle(List(1, 2, 3, 4, 5)), Bundle(List(2, 3, 4, 5, 6)))
bundles
  .map{ bundle => ("data" -> bundle.data)}
  .foreach{ j => println(compact(render(j)))}
//{"data":[1,2,3,4,5]}
//{"data":[2,3,4,5,6]}

OTHER TIPS

if messages can be any data you can extract those as JValues.

import net.liftweb.json._
import net.liftweb.json.JsonDSL._

val parsedJSON = parse(...)
val bundles = (parsedJSON \\ "bundle").extract[List[JValue]]
compact(render(bundles))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top