Nifi - Groovy Json脚本定义空属性

23c0lvtd  于 2022-11-28  发布在  其他
关注(0)|答案(2)|浏览(166)

我有一个Nifi Groovy脚本。将字段分配给nifi属性,但如果json值则定义为null 为空。如果json值为空,我希望将属性定义为空。
空属性如下所示;

我这样想;

这是我使用的脚本,

import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
    return;
}
def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>
session.read(flowFile,
    { inputStream ->
        def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
        def obj = slurper.parseText(text)
        obj.each {k,v ->
           attrs[k] = v.toString()
        }
    } as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)
cgfeq70w

cgfeq70w1#

flowFile = session.putAllAttributes(flowFile, attrs.collectEntries{k,v->[k,v?:'']})
klr1opcd

klr1opcd2#

这是我解决了它;

import org.apache.commons.io.IOUtils
import java.nio.charset.*
def flowFile = session.get();
if (flowFile == null) {
    return;
}
def slurper = new groovy.json.JsonSlurper()
def attrs = [:] as Map<String,String>
session.read(flowFile,
    { inputStream ->
        def text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
        def obj = slurper.parseText(text)
        obj.each {k,v ->

          if (v.toString()=="null")
          {
            attrs[k] = ''
          } else {
            attrs[k] = v.toString()
          }

        }
    } as InputStreamCallback)
flowFile = session.putAllAttributes(flowFile, attrs)
session.transfer(flowFile, REL_SUCCESS)

相关问题