You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:基于Groovy按ID关联合并两个JSON的实现方法

Groovy实现JSON按ID关联合并的简便方法

核心思路

先将SecondJson中的downloads数组转换为以id为键的映射表(Map),后续查找对应对象时能做到O(1)时间复杂度,避免嵌套循环降低效率;再遍历MainJson的ProductMaster数组,将每个产品的逗号分隔ID字符串转换为对应的对象数组,替换原字段。

示例输入与处理代码

假设你的输入JSON结构如下:

MainJson示例:

{
  "ProductMaster": [
    {
      "id": "prod1",
      "name": "Product 1",
      "downloads": "dl1,dl3"
    },
    {
      "id": "prod2",
      "name": "Product 2",
      "downloads": "dl2"
    }
  ]
}

SecondJson示例:

{
  "downloads": [
    {
      "id": "dl1",
      "url": "https://example.com/dl1",
      "type": "pdf"
    },
    {
      "id": "dl2",
      "url": "https://example.com/dl2",
      "type": "zip"
    },
    {
      "id": "dl3",
      "url": "https://example.com/dl3",
      "type": "docx"
    }
  ]
}

以下是Groovy实现代码:

import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

// 1. 解析JSON(如果是文件读取,替换为parse(new File('xxx.json')))
def mainData = new JsonSlurper().parseText('''{"ProductMaster": [{"id": "prod1","name": "Product 1","downloads": "dl1,dl3"},{"id": "prod2","name": "Product 2","downloads": "dl2"}]}''')
def secondData = new JsonSlurper().parseText('''{"downloads": [{"id": "dl1","url": "https://example.com/dl1","type": "pdf"},{"id": "dl2","url": "https://example.com/dl2","type": "zip"},{"id": "dl3","url": "https://example.com/dl3","type": "docx"}]}''')

// 2. 构建downloads的ID映射表,快速查找
def downloadMap = secondData.downloads.collectEntries { [(it.id): it] }

// 3. 处理每个产品的downloads字段
mainData.ProductMaster.each { product ->
    // 分割ID字符串,清理空值(处理多余逗号的情况)
    def downloadIds = product.downloads.split(',').collect { it.trim() }.findAll()
    // 替换为对应的对象数组,自动过滤不存在的ID(不需要过滤可去掉findAll)
    product.downloads = downloadIds.collect { downloadMap[it] }.findAll()
}

// 4. 输出合并后的JSON
println(new JsonBuilder(mainData).toPrettyString())

代码关键点说明

  • JsonSlurper/JsonBuilder:Groovy内置的JSON处理工具,无需额外依赖,直接解析和生成JSON
  • collectEntries:高效将数组转换为键值对映射,避免每次查找都遍历数组
  • split+trim+findAll:健壮处理逗号分隔的ID字符串,防止空格、空ID等异常情况
  • collect+findAll:快速将ID列表转换为对象数组,同时过滤无效ID(如果业务允许保留null,可移除findAll)

从文件读取JSON的调整

如果你的JSON存储在文件中,只需将解析部分替换为:

def mainData = new JsonSlurper().parse(new File('main.json'))
def secondData = new JsonSlurper().parse(new File('second.json'))

内容的提问来源于stack exchange,提问作者Kumar Badam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:15:41