Last active
February 17, 2021 20:55
-
-
Save lukas-h/24e1455d29af3dc26c67907755f8732f to your computer and use it in GitHub Desktop.
CSV to List<Map<String, String>> instead of the normal List<List<String>> scheme of the original csv package
This file contains hidden or 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
class CsvToMapConverter { | |
CsvToListConverter converter; | |
CsvToMapConverter( | |
{String fieldDelimiter = defaultFieldDelimiter, | |
String textDelimiter = defaultTextDelimiter, | |
String textEndDelimiter, | |
String eol = defaultEol, | |
CsvSettingsDetector csvSettingsDetector, | |
bool shouldParseNumbers, | |
bool allowInvalid}) { | |
converter = CsvToListConverter( | |
fieldDelimiter: fieldDelimiter, | |
textDelimiter: textDelimiter, | |
textEndDelimiter: textEndDelimiter, | |
eol: eol, | |
csvSettingsDetector: csvSettingsDetector, | |
shouldParseNumbers: shouldParseNumbers, | |
allowInvalid: allowInvalid); | |
} | |
List<Map<String, dynamic>> convert(String csv) { | |
List<List<dynamic>> list = converter.convert(csv); | |
List legend = list[0]; | |
List<Map<String, dynamic>> maps = []; | |
list.sublist(1).forEach((List l) { | |
Map<String, dynamic> map = {}; | |
for (int i = 0; i < legend.length; i++) { | |
map.putIfAbsent('${legend[i]}', () => l[i]); | |
} | |
maps.add(map); | |
}); | |
return maps; | |
} | |
} |
This file contains hidden or 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
// Instead of this output: | |
[ | |
["column 1", "column2", "column3"], | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
] | |
// you will get this output: | |
[ | |
{ | |
"column 1": 1, | |
"column 2": 2, | |
"column 3": 3, | |
}, | |
{ | |
"column 1": 4, | |
"column 2": 5, | |
"column 3": 6, | |
}, | |
{ | |
"column 1": 7, | |
"column 2": 8, | |
"column 3": 9, | |
}, | |
] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment