Question

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)
Was it helpful?

Solution

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)
  })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top