如何仅将JSON中空值Timestamp列替换为NULL后入库?
解决方案:仅将指定Timestamp列的空字符串转为NULL
不要用Replacetext做全局替换,这种方式无法区分字段类型。推荐用JoltTransformJSON或ExecuteScript处理器精准处理指定字段。
方法一:使用JoltTransformJSON处理器
Jolt可以通过JSON规范精准定位字段并修改,不会影响其他列。
配置Jolt Specification
将以下JSON作为Jolt规则配置到处理器中:
[ { "operation": "modify-overwrite-beta", "spec": { "*": { "regdate": ["=isNull(@(1,&))", ""], "due_date": ["=isNull(@(1,&))", ""], "start_date": ["=isNull(@(1,&))", ""] } } } ]
*表示遍历JSON数组中的每个对象=isNull(@(1,&))是Jolt内置函数:如果当前字段值为空字符串,就替换为null;否则保留原内容- 仅针对
regdate、due_date、start_date三个字段生效
处理后结果
[ { "name": "Tony", "age": 22, "regdate": "2022-07-01 02:15:15", "due_date": null, "start_date": null }, { "name": "Steve", "age": 21, "regdate": null, "due_date": "2022-03-01 05:22:15", "start_date": null }, { "name": "Peter", "age": 23, "regdate": null, "due_date": null, "start_date": "2021-08-06 02:20:15" } ]
方法二:使用ExecuteScript处理器(Groovy脚本)
如果需要更灵活的逻辑,可以用Groovy脚本直接操作JSON:
import groovy.json.JsonSlurper import groovy.json.JsonBuilder def flowFile = session.get() if (!flowFile) return // 读取JSON数据 def slurper = new JsonSlurper() def jsonData = slurper.parseText(flowFile.read().text) // 指定需要处理的Timestamp字段列表 def targetFields = ["regdate", "due_date", "start_date"] // 遍历修改指定字段 jsonData.each { item -> targetFields.each { field -> if (item[field] == "") { item[field] = null } } } // 写回处理后的JSON def builder = new JsonBuilder(jsonData) flowFile.write(builder.toString()) session.transfer(flowFile, REL_SUCCESS)
使用步骤
- 添加ExecuteScript处理器,选择Groovy作为脚本语言
- 将上述脚本粘贴到Script内容框中
- 连接输入输出流,运行即可得到目标结果
内容的提问来源于stack exchange,提问作者Ram
相关产品推荐
相关产品推荐

