如何在Apache NiFi中用JoltTransformJson将时间戳转指定日期字符串
问题概述
输入JSON数据:
{ "_id": "ir9RHG9nWqYAytwir", "userId": "rv4M5xfbz5wmugewp", "type": "online", "createdAt": 1684850821122 }
期望转换后的JSON:
{ "_id": "ir9RHG9nWqYAytwir", "userId": "rv4M5xfbz5wmugewp", "type": "online", "createdAt": "2023-05-22 14:05:33" }
(注:原期望输出中的单引号不符合JSON语法规范,最终输出会自动使用标准双引号)
你之前尝试的Jolt规范无效的原因是:Jolt本身不支持NiFi表达式语言(EL)的${createdAt:toDate(...)}语法,Jolt会将这段内容视为普通字符串,无法执行日期转换逻辑。
正确解决方法
方案一:结合UpdateAttribute与JoltTransformJSON
添加
UpdateAttribute处理器
设置新属性formattedCreatedAt,值为:${createdAt:toDate():format('yyyy-MM-dd HH:mm:ss')}该表达式会将毫秒级时间戳直接转换为指定格式的日期字符串。如果需要指定时区(比如UTC),可调整为:
${createdAt:toDate('UTC'):format('yyyy-MM-dd HH:mm:ss', 'UTC')}添加
JoltTransformJSON处理器
使用以下Jolt规则,将转换后的日期字段替换原createdAt,同时保留其他原有字段:[ { "operation": "shift", "spec": { "_id": "_id", "userId": "userId", "type": "type", "formattedCreatedAt": "createdAt" } } ]
方案二:在JoltTransformJSON中直接用NiFi EL生成规则
在JoltTransformJSON处理器的Jolt Specification属性中,使用NiFi表达式语言动态生成包含格式化日期的Jolt规则:
[ { "operation": "modify-overwrite-beta", "spec": { "createdAt": "${createdAt:toDate():format('yyyy-MM-dd HH:mm:ss')}" } } ]
NiFi会先解析EL表达式,将${...}替换为实际的日期字符串,再执行Jolt的modify-overwrite-beta操作,覆盖原createdAt字段,同时保留其他字段不变。
注意事项
- 确保时间戳对应的时区与NiFi默认时区一致,若不一致,必须在
toDate()和format()中明确指定时区,避免日期转换出现偏差。
内容的提问来源于stack exchange,提问作者Nikolay Smelov
相关产品推荐
相关产品推荐

