Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in a local csv file in javascript? [closed]

[EDIT] I solved the problem using D3, nevermind thanks!

So I have a csv file that looks something like this, and I need to import a local csv file into my client side javascript:

    "L.Name", "F.Name", "Gender", "School Type", "Subjects"
    "Doe",    "John",  "M",      "University",  "Chem I, statistics, English, Anatomy"
    "Tan",    "Betty",   "F",     "High School", "Algebra I, chem I, English 101"
    "Han",    "Anna",    "F",     "University",  "PHY 3, Calc 2, anatomy I, spanish 101"
    "Hawk",   "Alan",    "M",     "University",  "English 101, chem I" 

I eventually need do parse it and output something like:

Chem I: 3         (number of people taking each subject)
Spanish 101: 1 
Philosophy 204: 0 

But for now, I am stuck on just importing it into javascript.

My current code looks like this:

<!DOCTYPE html>  
<html>  
<body>
<h1>Title!</h1>
<p>Please enter the subject(s) that you wish to search for:</p>
<input id="numb" type="text"/> 
<button onclick="myFunction()">Click me to see! :) </button>
<script>
function myFunction() {
    var splitResearchArea = []; 
    var textInput = document.getElementById('numb').value; 
    var splitTextInput = textInput.split(",");

  for(var i =0; i<splitTextInput.length; i++) {
    var spltResearchArea = splitTextInput[i];
    splitResearchArea.push(spltResearchArea);
  }
}

I've researched and found some helpful links on Stackoverflow like this, this, and this but I'm new to javascript and I don't completely understand it. Should I use Ajax? FileReader? jQuery? What are the benefits of using one over the other? And how would you implement this in code?

But yeah, I'm just confused since I'm very new to javascript, so any help in the right direction would be great. Thank you!!

like image 765
ocean800 Avatar asked Apr 01 '15 14:04

ocean800


People also ask

How do I read a CSV file in JavaScript?

parse("http://example.com/bigfoo.csv", { download: true, step: function(row) { console. log("Row:", row. data); }, complete: function() { console. log("All done!"); } });

Can JavaScript parse CSV?

To convert or parse CSV data into an array , you need to use JavaScript's FileReader class, which contains a method called readAsText() that will read a CSV file data and parse the result as a string text.

Can I open CSV file in browser?

Click "File" and "Open," then use the Explorer window to locate the HTML file you want to add the CSV data to. Click the “Open” button.


3 Answers

Here is how to use the readAsBinaryString() from the FileReader API to load a local file.

Basically, just need to listen to change event in <input type="file"> and call the readFile function.

const fileInput = document.getElementById('csv')
const readFile = () => {
  const reader = new FileReader()
  reader.onload = () => {
    document.getElementById('out').innerHTML = reader.result
  }
  // start reading the file. When it is done, calls the onload event defined above.
  reader.readAsBinaryString(fileInput.files[0])
}

fileInput.addEventListener('change', readFile)
<div>
  <p>Select local CSV File:</p>
  <input id="csv" type="file" accept=".csv">
</div>
<pre id="out"><p>File contents will appear here</p></pre>

jsFiddle

like image 173
Jose Rui Santos Avatar answered Oct 10 '22 01:10

Jose Rui Santos


There are as many ways of accomplishing what you want as you could possibly imagine.

If I were doing this, I might start by splitting the input text into lines like so:

var lines = inputText.split('\n');

Then, I would extract the names of the headers from the first line. You need a function to read the values from each line.

// This assumes no commas in the values names.
function getCsvValuesFromLine(line) {
    var values = line[0].split(',');
    value = values.map(function(value){
        return value.replace(/\"/g, '');
    });
    return values;
}

var headers = getCsvValuesFromLine(lines[0]);

Next, I would loop over the remaining lines and create an array of objects representing the values in the lines.

lines.shift(); // remove header line from array
var people = lines.map(function(line) {
    var person = {};
    var lineValues = getCsvValuesFromLine(line);
    for (var i = 0; i < lines.length; i += 1) {
        person[headers[i]] = lineValues[i];
    }
    return person;
});

If this all works, you should end up with an array of objects representing the values in each line in your CSV.


The above is a rough outline of what the code might look like. I have not tested it and it certainly is not production ready, but I hope it gives you an idea of how to go about doing what you want.

I've used several built-in Javascript functions. I suggest looking them up on MDN if you're not familiar with them; they are good to know.

Finally, there is an odd quirk in Javascript with its automatic semi-colon insertion (a bad feature of the language, IMO). In order to avoid problems, do not put a new-line before an opening brace.

Always write

XXXX {
    ....
}

and don't write

XXXX
{
    ....
}
like image 36
Vivian River Avatar answered Oct 10 '22 02:10

Vivian River


i use this library from google: https://github.com/evanplaice/jquery-csv/ First - u have to

$.get(ur_csv_file_path);

and then use guide from page

like image 31
Legendary Avatar answered Oct 10 '22 03:10

Legendary