我想使用 scala lift 将数据从一个 json 合并到另一个 json。在下面的示例中,在“jsonGroups”中,我想计算所有组“tom”和“dan”的一部分并将 grpCount 插入“jsonNames”。println(newJson) 需要等于 finalOutput。什么是有效的方法来做到这一点?我知道这可以减少到更少的代码行
val jsonNames = """
{
"id" : "1B23423B",
"payload" : {
"list" : [ {
"age" : "30",
"name" : "tom",
}, {
"age" : "35",
"name" : "dan"
}]
}
}
"""
val jsonGroups = """
{
"id" : "1B23423B",
"payload" : {
"list" : [ {
"group" : "baseball",
"name" : "tom",
}, {
"group" : "basketball",
"name" : "tom"
}, {
"group" : "football",
"name" : "dan"
}, {
"group" : "hockey",
"name" : "dan"
}, {
"group" : "football",
"name" : "dan"
}]
}
}
"""
val finalOutput = """
{
"id" : "1B23423B",
"payload" : {
"list" : [ {
"age" : "30",
"name" : "tom",
"groupCnt" : 2
}, {
"age" : "35",
"name" : "dan",
"groupCnt" : 3
}]
}
}
"""
val jsGroups = parse(jsonGroups)
val groupList = jsGroups \ "payload" \ "list"
val groupMap = new HashMap[String, Int]
groupList.children.foreach { g =>
val group = (g \ "group").values.toString
val name = (g \ "name").values.toString
Option(groupMap.get(name)) match {
case Some(x) =>
groupMap.put(name, x + 1)
case None =>
groupMap.put(name, 1)
}
}
val jsNames = parse(jsonNames)
val newJson = jsNames.transform({
case dataObject @ JObject(fields) if fields.contains(JField("name", JString(name)))) =>
val groupCnt = groupMap.get(name)
dataObject.merge(("groupCnt" -> groupCnt))
})
println (pretty(render(newJson)))