Last active
March 9, 2021 20:50
-
-
Save crazy4groovy/8438827 to your computer and use it in GitHub Desktop.
A Groovy script that takes a CSV filePath (string), and turns it into a List of Maps (via groovycsv lib).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab('com.xlson.groovycsv:groovycsv:1.0') | |
import com.xlson.groovycsv.CsvParser | |
// a normally parsed csv can only be searched through ONCE | |
// this is used to create a "re-searchable" object (List of Maps) | |
List<Map> csv2List( String filePath, boolean shouldTrim = true, String charset = 'UTF-8' ) { | |
new File( filePath ).withReader(charset) { r -> | |
new CsvParser().parse( r ).with { csv -> | |
return csv.collect { line -> | |
line.columns.collectEntries { c, v -> | |
[ c, (shouldTrim ? line[ c ].trim() : line[ c ]) ] | |
} | |
} | |
} | |
} | |
} |
Holy cow, that's great! Thanks @timyates! Didn't even know about collectEntries - groovy :)
Added optional trimming to boot.
new CsvParser().parse(r).with { csv ->
csv.collect { PropertyMapper line ->
line.toMap()
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Careful to close the reader, how about: