如何在Apache NiFi中基于属性动态访问JSON嵌套键值?
在Apache NiFi中动态获取JSON嵌套属性值的方案
一、使用UpdateAttribute处理器实现
你之前的写法失败是因为NiFi表达式语言不会解析jsonPath函数参数内部的${keyname}占位符,它会把整个字符串原封不动传给JSONPath引擎,导致无法识别动态键名。可以通过字符串拼接构建完整的JSONPath来解决:
在UpdateAttribute中添加新属性,值设置为:
${timestamps:jsonPath(concat('$.[0].primary.', keyname))}
这里利用concat函数将固定的JSONPath前缀$.[0].primary.和keyname属性的值拼接成完整的路径,再传入jsonPath函数,就能动态获取对应键的时间戳。
二、替代方案:使用ExecuteScript处理器
如果上述方法在你的NiFi版本中存在兼容性问题,或者需要更复杂的JSON处理逻辑,可以用ExecuteScript处理器(推荐Groovy脚本):
- 配置ExecuteScript处理器,选择Groovy作为脚本语言
- 输入以下脚本(替换
targetAttribute为你要存储结果的属性名):
def flowFile = session.get() if (!flowFile) return // 获取输入属性 def timestampsStr = flowFile.getAttribute('timestamps') def targetKey = flowFile.getAttribute('keyname') // 解析JSON并取值 def jsonSlurper = new groovy.json.JsonSlurper() def jsonData = jsonSlurper.parseText(timestampsStr) def targetValue = jsonData[0].primary[targetKey] // 设置结果属性 flowFile = session.putAttribute(flowFile, 'targetAttribute', targetValue?.toString()) session.transfer(flowFile, REL_SUCCESS)
内容的提问来源于stack exchange,提问作者jaw325
相关产品推荐
相关产品推荐

