plain groovy to test script in groovyConsole:
import groovy.json.*
def parser = new JsonSlurper().setType(JsonParserType.LAX) //LAX to accept strings without double-quotes
def w = System.out
new StringReader('''date,name,department
2020-2-4,sachith,{"dep_name":"computer","location":"2323,3434"}
2020-2-5,nalaka,{"dep_name":"engineering","location":"3343,5454"}''').withReader{r->
r.eachLine{line, lineNum->
if(lineNum==1){
w<<line<<',lon,lat'<<'\n'
}else{
def row=line.split(',') //split line by coma
def json=row[2..-1].join(',') //join back to string starting from 3rd element
json = parser.parseText(json)
w<<"${row[0]},${row[1]},${json.dep_name},${json.location}"<<'\n'
}
}
}
now the same script modified for nifi ExecuteGroovyScript processor:
import groovy.json.*
def ff=session.get()
if(!ff)return
def parser = new JsonSlurper().setType(JsonParserType.LAX)
ff.write{streamIn,streamOut->
streamIn.withReader('UTF-8'){r-> //convert in stream to reader
streamOut.withWriter('UTF-8'){w-> //convert out stream to writer
//go line by line
r.eachLine{line, lineNum->
if(lineNum==1){
w<<line<<',lon,lat'<<'\n' //for the first line just add some headers
}else{
def row=line.split(',') //split line by coma
def json=row[2..-1].join(',') //join back to string starting from 3rd element
json = parser.parseText(json)
w<<"${row[0]},${row[1]},${json.dep_name},${json.location}"<<'\n'
}
}
}
}
}
REL_SUCCESS<<ff