My CSV data looks like this:
heading1,heading2,heading3,heading4,heading5 value1_1,value2_1,value3_1,value4_1,value5_1 value1_2,value2_2,value3_2,value4_2,value5_2 ...
How do you read this data and convert to an array like this using JavaScript?:
[ heading1: value1_1, heading2: value2_1, heading3: value3_1, heading4: value4_1 heading5: value5_1 ],[ heading1: value1_2, heading2: value2_2, heading3: value3_2, heading4: value4_2, heading5: value5_2 ] ....
I’ve tried this code but no luck!:
<script type="text/javascript"> var allText =[]; var allTextLines = []; var Lines = []; var txtFile = new XMLHttpRequest(); txtFile.open("GET", "file://d:/data.txt", true); txtFile.onreadystatechange = function() { allText = txtFile.responseText; allTextLines = allText.split(/rn|n/); }; document.write(allTextLines); document.write(allText); document.write(txtFile); </script>
Advertisement
Answer
NOTE: I concocted this solution before I was reminded about all the “special cases” that can occur in a valid CSV file, like escaped quotes. I’m leaving my answer for those who want something quick and dirty, but I recommend Evan’s answer for accuracy.
This code will work when your data.txt
file is one long string of comma-separated entries, with no newlines:
data.txt:
heading1,heading2,heading3,heading4,heading5,value1_1,...,value5_2
javascript:
$(document).ready(function() { $.ajax({ type: "GET", url: "data.txt", dataType: "text", success: function(data) {processData(data);} }); }); function processData(allText) { var record_num = 5; // or however many elements there are in each row var allTextLines = allText.split(/rn|n/); var entries = allTextLines[0].split(','); var lines = []; var headings = entries.splice(0,record_num); while (entries.length>0) { var tarr = []; for (var j=0; j<record_num; j++) { tarr.push(headings[j]+":"+entries.shift()); } lines.push(tarr); } // alert(lines); }
The following code will work on a “true” CSV file with linebreaks between each set of records:
data.txt:
heading1,heading2,heading3,heading4,heading5 value1_1,value2_1,value3_1,value4_1,value5_1 value1_2,value2_2,value3_2,value4_2,value5_2
javascript:
$(document).ready(function() { $.ajax({ type: "GET", url: "data.txt", dataType: "text", success: function(data) {processData(data);} }); }); function processData(allText) { var allTextLines = allText.split(/rn|n/); var headers = allTextLines[0].split(','); var lines = []; for (var i=1; i<allTextLines.length; i++) { var data = allTextLines[i].split(','); if (data.length == headers.length) { var tarr = []; for (var j=0; j<headers.length; j++) { tarr.push(headers[j]+":"+data[j]); } lines.push(tarr); } } // alert(lines); }