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

Apache NiFi中Groovy脚本JSON处理及数据匹配问题求助

Apache NiFi Groovy脚本处理JSON匹配提取方案

1. 先处理FlowFile内容(提取目标关键词)

你的FlowFile内容是带双引号的"COVID-19",得先把首尾引号去掉,转成纯文本关键词:

// 读取FlowFile内容
def flowFileContent = session.read(flowFile).getText("UTF-8")
// 去掉首尾双引号,得到干净的关键词
def targetKeyword = flowFileContent.trim().replaceAll(/^"|"$/, "")

2. 处理Response数据(解析非标准JSON)

注意你的Response数据开头带了Response前缀,不是标准JSON结构,必须先去掉前缀再解析:

// 假设Response数据是你获取到的字符串(比如从属性或其他来源读取)
def responseStr = '''Response
{
  "Name" : {
    "COVID-19" : [ "88" ],
    "Fever" : [ "40" ]
  }
}'''
// 去掉开头的"Response"及后续空白字符,得到标准JSON
def cleanJsonStr = responseStr.replaceFirst(/^Response\s*/, "")
// 解析JSON为Groovy可操作的Map对象
def jsonSlurper = new groovy.json.JsonSlurper()
def responseMap = jsonSlurper.parseText(cleanJsonStr)

3. 匹配SID变量并提取目标ID

s3data里的SID值和FlowFile关键词一致,直接用变量匹配取值:

// 假设已获取到s3data中的SID变量
def sidValue = s3data.SID
// 匹配关键词,提取对应的ID(注意JSON里是数组,取第一个元素)
def targetId = null
if (sidValue == targetKeyword && responseMap.Name.containsKey(sidValue)) {
    targetId = responseMap.Name[sidValue][0]
    // 如果需要数字类型,可转成Integer:targetId as Integer
}

4. 将结果传递给后续流程

把提取到的ID要么写入FlowFile内容,要么设置成属性供后续流程使用:

if (targetId) {
    // 方式1:写入FlowFile内容
    flowFile = session.write(flowFile, { outputStream ->
        outputStream.write(targetId.getBytes("UTF-8"))
    } as OutputStreamCallback)
    // 方式2:设置为FlowFile属性
    flowFile = session.putAttribute(flowFile, "target.id", targetId)
}
// 提交会话,流转到成功分支
session.transfer(flowFile, REL_SUCCESS)

注意事项

  • 检查Response的JSON结构是否正确,你的示例里少了一个闭合括号,实际使用时要确保JSON格式合法
  • 处理FlowFile内容时,记得用trim()去除多余空格,避免引号处理不彻底
  • 变量匹配时要注意大小写、特殊字符完全一致,否则会匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:00:16