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

如何在Groovy中替换JSON值并生成批量条目(Apache NiFi场景)

解决方案

方案一:Groovy脚本实现(ExecuteScript组件)

步骤说明

  1. 提前配置:
    • 已通过ExtractText将API返回的员工列表JSON字符串存入FlowFile的Response属性
    • 将模板JSON字符串存入FlowFile的Template_JSON属性(示例模板:{"Emp_Id":"All","Name":"XXX","Dept":"YYY"})
  2. 在ExecuteScript组件中选择Groovy语言,粘贴以下脚本:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

def flowFile = session.get()
if (!flowFile) return

try {
    // 获取属性中的API响应和模板JSON
    def responseJson = flowFile.getAttribute('Response')
    def templateJson = flowFile.getAttribute('Template_JSON')
    
    // 解析API响应,提取员工ID列表
    def slurper = new JsonSlurper()
    def empList = slurper.parseText(responseJson)
    // 根据API返回结构调整提取逻辑:若返回单层数组如["1001","1002"],直接用def empIds = empList
    def empIds = empList.collect { it.Emp_Id }
    
    // 遍历员工ID,生成对应数据条目
    def templateObj = slurper.parseText(templateJson)
    empIds.each { empId ->
        templateObj.Emp_Id = empId
        def newJson = new JsonBuilder(templateObj).toPrettyString()
        
        // 创建新FlowFile并写入内容
        def newFlowFile = session.create(flowFile)
        newFlowFile = session.write(newFlowFile, { outputStream ->
            outputStream.write(newJson.getBytes('UTF-8'))
        } as OutputStreamCallback)
        
        // 传递原属性(按需调整)
        newFlowFile = session.putAllAttributes(newFlowFile, flowFile.attributes)
        session.transfer(newFlowFile, REL_SUCCESS)
    }
    
    session.remove(flowFile)
} catch (Exception e) {
    log.error("处理失败:${e.getMessage()}", e)
    session.transfer(flowFile, REL_FAILURE)
}

注意事项

  • 必须根据API返回的实际JSON结构调整员工ID的提取逻辑,确保empIds能正确拿到所有目标ID。
  • 若模板无需动态配置,可直接在脚本中定义模板对象,比如def templateObj = [Emp_Id: "All", Name: "XXX", Dept: "YYY"]。

方案二:无代码组件组合方案(规避脚本报错)

如果不想编写脚本,可通过NiFi原生组件组合实现:

  1. SplitJson:配置Json Path Expression为$[*].Emp_Id,Destination选择Attribute并设置属性名empId,将Response中的员工ID列表拆分为单个FlowFile,每个FlowFile携带对应员工ID。
  2. ReplaceText:设置Search Value为"All",Replacement Value为"${empId}",Search Mode选Literal,完成模板中Emp_Id字段的替换。
  3. 可选:MergeContent:若需要将所有生成的条目合并为单个JSON数组格式的FlowFile,可在ReplaceText后添加该组件,按对应规则合并。

这种方案完全依赖NiFi原生功能,无需脚本,从根源避免了脚本引擎的字节码生成报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:45:03