A Simple Function That Parses a CSV String Into JSON

0 comments

function parseCSV(str){
 
 
 var csvArr = str.replace(/","/igm,",,,").split("\n");
 //takes input CSV string and replaces all the separators
 //with triple commas to prevent confusion with commas
 //that may be part of a record and not a seperator,
 //then splits at every newline to create an array of records
 
 
 var key = csvArr[0].split(',,,');
 //the key is the first line, which is used to map
 //the other records 
 
 var csvRecords = new Array();
 //main array for storing data
 
 
 csvArr.pop(); 
 (csvArr[csvArr.length-1]) ? csvArr.shift() : false
 //first entry in csvArr is the key, remove it
 //last entry is typically a blank string, remove it
 
 for(var i=0;i<csvArr.length;i++){
  //traverses all valid records in csvArr
  
  csvRecords[i] = { };
  
  var rec = csvArr[i].split(',,,');
  //rec is set anew for each row in the csv file
  
  for(var x=0;x<csvArr[i].length;x++){
   
   csvRecords[i][key[x]] = rec[x];
   //for each row in csvArr, set the obj property
   //to the correct entry from the key array
   //and set the property value to the correct
   //value from rec
  }
 }
 return csvRecords;
 //all done
}

Welcome To The Self-Taught Web Developer Blog

1 comments

I am a self-taught web developer. I never had any formal schooling (except for one 'Intro to C++' class). Every technique, every thing I know about developing websites comes from Google. Yep, anytime I wanted to do something I didn't know how to do, Google would eventually give me an answer to my question. So little by little I built my knowledge about web technologies until I began working full time as a web dev.

I write almost exclusively in php, javascript, and jquery. There are other languages out there on the web, and I may learn them at some point. But for right now, this is where I'm at. The problem with being a self-taught web dev is that no one told me what the "right way" to do something was. So my first webpages were HTML 4 documents, while everyone else was using transitional XHTML. No one was there to tell me what the "accepted way" to do something was. My purpose in making this blog is helping others just getting there start in web development get there much quicker.

I got my first taste of the web at htmlgoodies.com. It's not a bad site, but not best when learning "best practice" procedures and such. Anyway, I didn't know any better. If you are eager for more web help, w3schools.com is top notch. They have a lot of good tutorials and everything is updated with the most current web standards. Tomorrow's post is on starting a simple HTML page. You've probably heard of or seen DOCTYPES, but they just look jumbled and confusing. I'll sort out the mess for you, starting tomorrow.