What is a better way to transform in Scala lift JValue?

416 views Asked by At

I am given js1 as a string. I want to nest "a", "b", "c" under "abc". I feel like this can be done a few lines of code. What is a better way to do this below?

val js1 = """
{
    "name" : "test",
    "a" : true,
    "b" : true,
    "c" : true,
    "d" : true,
    "f" : true,
    "g" : true,
    "h" : true,
}
""" 

val jsGroups = parse(js1)

val a = (jsGroups \ "a").values.toString.toBoolean
val b = (jsGroups \ "b").values.toString.toBoolean
val c = (jsGroups \ "c").values.toString.toBoolean
val abc = ("a" -> a) ~ ("b" -> b) ~ ("c" -> c)
val r = jsGroups.remove { x =>
  x match {
    case JField("a", bool) => true
    case JField("b", bool) => true
    case JField("c", bool) => true
    case _ => false
  }

}
val newJs = r.merge(JObject(List(JField("abc", abc))))
println(pretty(render(newJs)))

output must be

{ "name":"test", "d":true, "f":true, "g":true, "h":true, "abc":{ "a":true, "b":true, "c":true } }

1

There are 1 answers

2
flavian On

The simplest way is to use a case class.

import net.liftweb.json.{ DefaultFormats, Extraction, JsonParser } 
case class Abc(a: Boolean, b: Boolean, c: Boolean)
implicit val formats = DefaultFormats

// to serialize to JValue
val test = Abc(true, true, true)
Extraction.decompose(test)

// to parse from String
JsonParser.parse("""{a: true, b: true, c: true}""").extract[Abc]