在任何人将此标记为重复之前,我已经检查过这个问题: Remove duplicates and merge JSON objects . (从那里复制的例子)
我正在处理一个涉及合并 json 的案例,如下例所示,
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
}
]
},
{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 21,
"nodeName" : "test2"
}
]
}]
直到叶节点之类的东西,
[{
"id" : 1,
"name" : "abc",
"nodes" :[
{
"nodeId" : 20,
"nodeName" : "test1"
},
{
"nodeId" : 21,
"nodeName" : "test2"
},
]
}]
我可以通过递归比较节点并手动合并到一个对象并最终转换为json字符串来使用暴力方法。我想知道是否有更好的方法使用 json4s 来做到这一点。 更多上下文,这是一个scala项目,有1000个json要合并成一个,它们可能有嵌套的复杂结构,如数组和对象。
这里的合并意味着添加到重复节点上预先存在的数据而不是覆盖它们,如上例所示。
我也考虑过使用树,但进展不大。
最佳答案
您可以使用合并
操作:
def main(args: Array[String]): Unit = {
val json = """[{
| "id" : 1,
| "name" : "abc",
| "nodes" :[
| {
| "nodeId" : 20,
| "nodeName" : "test1"
| }
| ]
| },
| {
| "id" : 1,
| "name" : "abc",
| "nodes" :[
| {
| "nodeId" : 21,
| "nodeName" : "test2"
| }
| ]
| }]""".stripMargin
val jsonArray = parse(json).asInstanceOf[JArray]
val res = jsonArray.arr.reduceLeft{(x,y) => x merge y}
println(pretty(render(res)))
}
哪个输出:
{
"id":1,
"name":"abc",
"nodes":[{
"nodeId":20,
"nodeName":"test1"
},{
"nodeId":21,
"nodeName":"test2"
}]
}
关于json - 使用 JSON4S 在重复节点上合并/组合 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52080472/