Nifi:如何在 JSON 中写入 sub/nested 元素

Nifi: How to write sub/nested element in JSON

我有一个传入的 Nifi 流文件,看起来像这样

{"filename":"ok.txt.2018-01-27-16-18-03-290","test":"{\"filename\":ok.txt,\"test\":23}","timestamp":"Sat Jan 27 16:18:03 UTC 2018"}

我想添加一个 sub/nested 元素 "test": { "text":"Hello world","Country":"Espana"} 到 "test"元素。换句话说,我希望我的 JSON 输出看起来像

{"filename":"ok.txt.2018-01-27-16-18-03-290","test":"{\"filename\":ok.txt,\"test\":23, "text": {"Hello world","Country":"Espana"}}","timestamp":"Sat Jan 27 16:18:03 UTC 2018"}

是否可以在 Nifi 中向 JSON 添加子元素?

谢谢

您可以通过以下代码使用 ExecuteGroovyScript 1.5.0 处理器

import groovy.json.*

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

ff.write{rawIn,rawOut->
    //parse json from input stream of the flow file
    def json = rawIn.withReader("UTF-8"){reader-> 
        new JsonSlurper().parse( reader )
    }
    //modify json 
    json."test" = [
            "text"     :"Hello world",
            "Country"  :"Espana"
        ]
    //write json to flow file output stream
    rawOut.withWriter("UTF-8"){writer->
        new JsonBuilder(json).writeTo(writer)
    }
}

REL_SUCCESS << ff