json - 使用 JSON4S 在重复节点上合并/组合 JSON

标签 json algorithm scala json4s

在任何人将此标记为重复之前,我已经检查过这个问题: 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/

相关文章:

python - 使用 Python 将 Excel 转换为 JSON

json - 将盒装特征的向量序列化为 JSON

algorithm - 大O,您如何计算/近似?

scala - 使用 Guice 绑定(bind)/注入(inject) Scala 函数(不是整个类)?

c# - 使用传入 Webhook C# 将图像发布到 Slack

javascript - JavaScript 中的美化函数

algorithm - 这两个广度优先搜索问题有何不同

找到最小数 N 以在总和低于 N 的 X 子集中划分堆栈值的算法

scala - Spark:DataFrame如何在groupBy结果上使用Sum

带有和不带有类型归属的最终 val 的 Scala 不一致行为