-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv_to_json_parser.groovy
83 lines (62 loc) · 2.5 KB
/
csv_to_json_parser.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//IMPORTANT NOTE: ***THIS PARSER ASSUMES ALL FIELDS OF CSV RECORD(S) IS OF STRING DATA TYPE ***
import org.apache.commons.io.IOUtils
import java.nio.charset.StandardCharsets
import groovy.json.JsonOutput
//get current flowfile
def flowFile = session.get()
if(!flowFile) return
def rowInfo = "" //to store current row being processed
try
{
def rowDelimiter = rowDelimiter.value // dynamic executescript attribute containing regex pattern. eg /\n/
def colDelimiter = colDelimiter.value //dynamic executescript attribute containing regex pattern.
flowFile = session.write(flowFile,{inputStream,outputStream ->
//read csv data from flow file
def csvData = IOUtils.toString(inputStream,StandardCharsets.UTF_8)
//split csv data by row delimiter
def rows = csvData.split(rowDelimiter)
//get columsn headers
def colHeaders = rows[0].split(colDelimiter)
def lstOutput = [] //init groovy list object
for(rowIndex=1;rowIndex <rows.size();rowIndex++)
{
//current record
def row = rows[rowIndex].split(colDelimiter)
//store current row being processed for debugging purpose (optional)
rowInfo = "current row ${rowIndex} - ${rows[rowIndex]}"
def mp = [:] // groovy map object to hold current record in key / value pairs
//iterate columsn of current row
for(colIndex=0;colIndex < colHeaders.size();colIndex ++)
{
//current column name
def colName = colHeaders[colIndex]
if(colIndex < row.size()) //to handle bug in groovy split() which ignores last column if its empty
{
mp[colName] = row[colIndex]
}
else
{
mp[colName] = ""
}
}
//add current record to groovy list
lstOutput.add(mp)
}
//convert groovy list object to json string
def jsonOutput = JsonOutput.toJson(lstOutput)
//pretty print json
jsonOutput = JsonOutput.prettyPrint(jsonOutput)
//write json string to output stream of flow file
outputStream.write(jsonOutput.getBytes(StandardCharsets.UTF_8)
} as StreamCallback)
//transfer flow file to success
session.transfer(flowFile,REL_SUCCESS)
}
catch(e)
{
//add attributes containing error details to debug erring row
flowFile = session.putAttribute(flowFile,"csv_json_parse_error",e.toString())
flowFile = session.putAttribute(flowFile,"current_row",rowInfo)
//transfer flowfile to failure
session.transfer(flowFile,REL_FAILURE)
}