How do I transform json using scala lift?

272 views Asked by At

How do I transform the json below using scala lift based on a sibling attribute? In the json below, I want to encode the value in "value" attribute if sibling attribute "type" is "html"

val json = """
{
    "id" : "1B23423B",
    "payload" : {
        "list" : [ {
            "name" : "test",
            "data" : [ {
                "value" : "Some html",
                "type" : "html",
            }, {
                "value" : "some text",
                "type" : "text"
            }]
         }]
    }
}
"""
def encode(s:String):String = s + "encoded"
val newjson = js.transform { 
    case x if x == JField("type",JString("html")) => // somehow encode value??
}

println(newjson)
1

There are 1 answers

0
Bask.ws On BEST ANSWER

Here is on of the possible solutions:

1) first find data json with type html

2) transform json value child

  val parsed = JsonParser.parse(jsonString)  

  def encode(s:String):String = s + "encoded"

  private def encodeValue(dataObject: JValue) = dataObject.transform{
    case JField("value", JString(value)) => JField("value", JString(encode(value)))
  }

  val newJson = parsed.transform({
    case dataObject @ JObject(fields) if fields.contains(JField("type", JString("html"))) => encodeValue(dataObject)
  })