如何在NiFi中用JsonPath获取位置可变的指定数组元素值
NiFi中获取动态位置数组元素的JsonPath解决方案
问题背景
给定以下JSON结构:
{"phones": [ { "type": "H", "countryCode": "US", "number": "1113802141", "operation": "INSERT" }, { "type": "M", "countryCode": "US", "number": "2225336782", "operation": "INSERT" }, { "type": "B", "countryCode": "US", "number": "3337274003", "operation": "INSERT" } ]}
需要获取type='M'的数组元素的operation字段值,但常规JsonPath表达式$.phones[?(@.type=='M')].operation在NiFi的Evaluate JsonPath组件中无效,且该元素在数组中的位置不固定。
可行解决方案
方案1:使用Jolt Transform JSON组件(推荐)
NiFi的Jolt组件对动态JSON匹配支持更友好,适合处理这类场景。配置步骤:
- 选择
JoltTransformJSON组件 - 设置Jolt Specification为:
[ { "operation": "shift", "spec": { "phones": { "*": { "type": { "M": { "@(2,operation)": "mobile_operation" } } } } } } ]
该配置会遍历phones数组,匹配所有type为M的元素,将对应的operation字段提取到mobile_operation节点中,后续可通过Evaluate JsonPath或属性提取获取该值。
方案2:调整Evaluate JsonPath组件配置
部分NiFi版本对JsonPath过滤器的语法支持有差异,可尝试以下调整:
- 将表达式改为双引号匹配:
$.phones[?(@.type == "M")].operation - 在组件的Return Type下拉框中选择
Scalar(仅需单个值时)或JSON(需返回匹配数组时) - 若存在多个匹配值,可结合
SplitJson组件拆分后再提取目标字段
方案3:使用ExecuteScript组件编写脚本处理
通过Groovy或Python脚本直接解析JSON并提取目标值,以Groovy为例:
import groovy.json.JsonSlurper def flowFile = session.get() if (!flowFile) return def jsonContent = flowFile.read().getText("UTF-8") def jsonObj = new JsonSlurper().parseText(jsonContent) def targetOperation = jsonObj.phones.find { it.type == 'M' }?.operation flowFile = session.putAttribute(flowFile, 'mobile_operation', targetOperation ?: '') session.transfer(flowFile, REL_SUCCESS)
该脚本读取FlowFile的JSON内容,找到type为M的元素并提取operation值,将其设置为FlowFile的属性mobile_operation,后续可直接使用该属性。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

