简体   繁体   English

如何使用scala lift转换json?

[英]How do I transform json using scala lift?

How do I transform the json below using scala lift based on a sibling attribute? 如何使用scala lift基于兄弟属性转换下面的json? In the json below, I want to encode the value in "value" attribute if sibling attribute "type" is "html" 在下面的json中,如果兄弟属性“type”是“html”,我想在“value”属性中编码值

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)

Here is on of the possible solutions: 以下是可能的解决方案:

1) first find data json with type html 1)首先找到类型为html的数据json

2) transform json value child 2)变换json值子

  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)
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM