Search code examples
groovygroovyshellgroovy-console

How to sort data from a JSON ARRAY (list of maps) and export them to excel/csv


I have a JSON array (list of maps) similar to:

def listOfMap = [[TESTCASE:1, METHOD:'CLICK', RESULT:'PASS'], 
      [TESTCASE:2, METHOD:'CLICK', RESULT:'FAIL'], 
      [TESTCASE:3, METHOD:'CLICK', RESULT:'FAIL'], 
      [TESTCASE:4, METHOD:'TYPETEXT', RESULT:'FAIL']]

I want to generate a report with unique method names in one column and their % failure in another column and export to csv/excel/html. The report should be in the following pattern

Report :

1) What is the shortest groovy code possible to achieve this?
2) How can we export the data to excel/csv?

I have these code snippets available but unable to connect the dots

a) To get the list of unique methods listOfMap.METHOD.unique()

b) To get the count of runs for each METHOD (here i want to loop through above output) listOfMap.count { map -> map.METHOD == 'CLICK'}

c) To get the FAIL count of all methods from above list listOfMap.count { map -> map.METHOD == 'CLICK' && map.RESULT == 'FAIL' }

Now i want to calculate: (Count of FAIL result for each METHOD / Total Runs of each METHOD * 100)


Solution

  • Something like this:

    def percentage (map){
         (map.FAIL ?: 0) / ((map.PASS ?: 0) + (map.FAIL ?: 0)) * 100
    }
    
    def result = listOfMap.groupBy{it.METHOD}
                          .collectEntries{[(it.key) : percentage(it.value.countBy{it.RESULT})]}
    
    def outputCsv = new File('/pathToReport/report.csv')
    outputCsv.write "S.No;MethodName;Failture %\n"
    result.eachWithIndex{ entry, index ->
       outputCsv << "${index+1};${entry.key};${entry.value}\n"