NiFi中JOLT V0.1.1转换单元素JSON数组时输出异常问题
解决NiFi中JOLT V0.1.1转换JSON的单元素null及数组去重问题
问题分析
- 单元素数组输出null:JOLT V0.1.1在处理单元素数组时,会自动将数组降级为单个对象,导致原规则中依赖数组遍历的路径失效,最终输出null。
- NiFi中出现大量null数组元素:通常是规则未精准过滤非目标类型元素,遍历过程中为不匹配
type: matching-indicators的元素生成了null字段,最终被保留在结果数组中。
解决方案
方案1:调整JOLT规则适配单/多元素数组,并过滤null
通过shift操作精准筛选目标元素,结合remove操作清理null值,同时确保数组结构在单元素场景下正常保留。
最终JOLT规则
[ { "operation": "shift", "spec": { "included": { "*": { "type": { "matching-indicators": { "@(2,name)": "result[&3].name", "@(2,label)": "result[&3].label", "@(2,score)": "result[&3].score" } } } } } }, { "operation": "remove", "spec": { "result": { "*": { "null": "" } } } }, { "operation": "shift", "spec": { "result": { "*": { "@": "[#2]" } } } } ]
方案2:针对单元素场景的兼容处理
如果原规则在多元素场景正常,仅单元素失效,可在shift操作前添加default操作,强制将included字段转为数组(避免单元素时被降级为对象):
[ { "operation": "default", "spec": { "included": [] } }, { "operation": "shift", "spec": { "included": { "*": { "type": { "matching-indicators": { "@(2,name)": "[]", "@(2,label)": "[]", "@(2,score)": "[]" } } } } } }, { "operation": "shift", "spec": { "*": { "*": "[&1].&" } } } ]
方案3:NiFi后置处理器清理null
如果JOLT规则难以调整,可在JoltTransformJSON之后添加ExecuteScript处理器,用Groovy脚本过滤数组中的null元素:
import groovy.json.JsonSlurper import groovy.json.JsonBuilder def flowFile = session.get() if (!flowFile) return def slurper = new JsonSlurper() def json = slurper.parse(flowFile.read()) if (json.result instanceof List) { json.result = json.result.findAll { it != null && !it.isEmpty() } } def builder = new JsonBuilder(json) flowFile.write("UTF-8", builder.toString()) session.transfer(flowFile, REL_SUCCESS)
验证要点
- 测试单元素
included数组输入,确认输出数组包含正确字段而非null - 测试混合类型的
included数组,确认仅matching-indicators类型元素被保留,无null条目
内容的提问来源于stack exchange,提问作者Mariano Baudena
相关产品推荐
相关产品推荐

