You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NiFi Groovy Json脚本:将JSON null值转为空属性的技术问询

解决NiFi Groovy脚本中JSON null值转空字符串属性的问题

问题描述

现有NiFi Groovy脚本可将JSON字段映射为NiFi属性,但当JSON字段值为null时,会生成值为字符串"null"的属性,需求是将这类JSON null值转换为空字符串属性。

原脚本(存在问题)

import groovy.json.JsonSlurper

def flowFile = session.get()
if (!flowFile) return

def slurper = new JsonSlurper()
try {
    flowFile = session.read(flowFile, { inputStream ->
        def json = slurper.parse(inputStream)
        json.each { key, value ->
            flowFile = session.putAttribute(flowFile, key, value?.toString())
        }
    } as InputStreamCallback)
    session.transfer(flowFile, REL_SUCCESS)
} catch (e) {
    log.error("Error processing JSON", e)
    session.transfer(flowFile, REL_FAILURE)
}

原脚本中,当JSON值为null时,value?.toString()会返回字符串"null",导致NiFi属性值为null而非空字符串。

修改后的脚本(实现需求)

import groovy.json.JsonSlurper

def flowFile = session.get()
if (!flowFile) return

def slurper = new JsonSlurper()
try {
    flowFile = session.read(flowFile, { inputStream ->
        def json = slurper.parse(inputStream)
        json.each { key, value ->
            // 核心修改:将null值转换为空字符串,非null值保留原toString结果
            def attrValue = value != null ? value.toString() : ""
            flowFile = session.putAttribute(flowFile, key, attrValue)
        }
    } as InputStreamCallback)
    session.transfer(flowFile, REL_SUCCESS)
} catch (e) {
    log.error("Error processing JSON", e)
    session.transfer(flowFile, REL_FAILURE)
}

核心修改点:使用三元运算符判断值是否为null,如果是则赋值为空字符串,否则保留原值的字符串形式。也可以用Groovy的Elvis运算符简化为value?.toString() ?: "",效果一致。

效果对比

修改前(JSON null生成null属性)

修改前效果:JSON字段为null时,NiFi属性值显示为"null"

修改后(JSON null生成空字符串属性)

修改后效果:JSON字段为null时,NiFi属性值为空字符串

内容的提问来源于stack exchange,提问作者veganzombie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:50:28