Code: Select all
;CSVtoDict(file) takes a csv and outputs a dictionary. Took ages as i didn't understand that array.Insert() needs to have a reference for each new object e.g. array.Insert(1, object), array.Insert(2, object) and that each object needs to be re-dimensionalised else it'll always only point to the last set value
;origional https://www.autohotkey.com/boards/viewtopic.php?t=5251
;updated to work with commas. YOU MUST ESCAPE CELLS WITH A COMMA BY SURROUNDING THE WHOLE CELL IN " ".
/*
EXAMPLE DATA(SAVE THIS AS A CSV):
accountId,dealerName,dealerAddress,POCName,POCTN,POCEmail,DPMName,DPMEmail,DPMTN,accountType,DualPartner,engagement,advertising,3pt,SEO,CustomHUD,MPRPrefType,Statisfaction,Group,Lat,Long,TimeZone,OEM,Contacts,Notes
"coolestdealerever","Coolest Car Dealer Ever","2300 marsh ln,dallas NM 75085","1234567890","Nathan Northcut","1234567890","noreply@noreply.com","Courtney Douglas","noreply@noreply.com","1234567890","Lincoln",,"Engaged","Mix","No","No","none","Either","Satisfied","Retail","29","33","America/Chicago","Lincoln","Lance Willis|noreply@noreply.com|,secondContact|noreply@noreply.com|1234567891","this is just a set of notes here!"
*/
FileSelectFile,csvFilePath,1,,Select the CSV file to import your accounts from,*.csv
if(csvFilePath != "") {
accountArray:= CSVtoDict(csvFilePath)
msgbox, % accountArray[1]["accountId"] . " | " . accountArray[1]["dealerName"]
}
CSVtoDict(File)
{
array := []
arrayOfHeaders := []
arrayOfData := []
Loop, Read, %file%
{
If (A_Index == 1) { ;headers
loop,parse,A_LoopReadLine, csv
{
arrayOfHeaders.push(A_LoopField)
}
}
Else
{
arrayOfData := {}
array[A_Index - 1] := {} ;due to the way AHK works, you need to separate object references. http://www.autohotkey.com/board/topic/77221-associative-array-of-objects-help/
loop,parse,A_LoopReadLine, csv ;use a loop,parse so we can correctly handle literal strings & commas
{
arrayOfData.push(A_LoopField)
}
subdict := {} ;This line is needed create a new object reference to subdict in memory (We need to clear subdict every iteration or else our first dataset will repeat)
For index, value in arrayOfData ;for all columns in one row, create dict of {HeaderName: DataItem, HeaderName: DataItem}
{
subdict[arrayOfHeaders[index]] := value ;make a dictionary of {HeaderName: DataItem}
}
array[A_Index - 1] := subdict ;==array.Insert(A_Index - 1, subdict) ;subdict := {} is needed above else this line just adds the reference to the subdict, not the new values
}
}
Return array
}