SD31 SD31 - 9 months ago 113
Groovy Question

Retrieve data by Ignoring null values and header row from csv file

Working on

Groovy Script
in soapui 5.3.0 and facing the below issue while extracting the values from file to a list.

Purpose of below code is, the list retrieved has to be compared with another list with valid values only.

Attaching the code snippet and the sample csv file for reference.

code to retrieve the values:

def DBvalue= context["csvfile"] //csv file containing the data
def count= context["dbrowcount"] //here the rowcount is 23
for (i=0;i<count;i++) {
def lines= ""
lines= DBvalue.text.split('\n')
list<string> rows = lines.collect{it.split(';)}
log.info "list is"+rows
}


Sample CSV file on which am working contains 600 column of data with 23 rows

abc;null;1;2;3;5;8;null
cdf;null;2;3;6;null;5;6
hgf;null;null;null;jr;null;II


Currently my code is fetching the below output:

[[abc,null,1,2,3,5,8,null]]
[[abc,null,1,2,3,5,8,null]]
[[abc,null,1,2,3,5,8,null]]


Desired output:

[1,2,3,5,8]
[2,3,6,5,6]
[jr,II]

Rao Rao
Answer Source

You should be able achieve it with below, and follow in-line comments.

//Provide your file path; change if needed
def file = new File('/tmp/test.csv')

//To hold all the rows
def list = []

//Change delimiter if needed
def delimiter = ';'

file.readLines().eachWithIndex { line, index ->
    if (index) {
        //Get the row data by split, filter
        def lineData = line.split(delimiter).findAll { 'null' != it && it}
        log.info lineData
        list << lineData
    }
}

//Print all the row data
log.info list

Input:

enter image description here

Output:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download