javascriptjquerycsvjquery-csv

Read .csv file to object/array in javascript


I'm trying to do something that I think is fairly simple, but doesn't seem to be working. I have a .csv file in the same directory as my script file. I want to create an object or an array using the data from the .csv file. How do I access the local file using javascript?

Sorry for the lack of code, but I don't even know which route to go down; I've tried .get and ajax and this plugin but I just don't know what I'm doing. Could someone give me a clear example of how to load the file and print it in a div?


Solution

  • In order to simulate a static file server, you can run an http server using python on the command line. This is necessary to use ajax requests.

    python -m SimpleHTTPServer  
    

    Or if you have python 3

    python -m http.server
    

    Now there are two parts to getting that file to a webpage. 1) make an ajax request, 2) parse the csv. There are many different libraries that implement ajax requests, but in this case you might find the easiest out of the box solution which combines both is d3.js.

    d3.csv("filename.csv", function(err, data) {
    
        // csv is parsed into an array of objects, as data
    
    });
    

    Of course this will only work if you are loading your page from localhost.

    EDIT:

    Make sure you run your http server from the location of your index.html file. then the request you make in the d3.csv function is relative to index. finally, the data is only available inside the callback, and any error message (or null) will be put inside the err argument.

    Project
    |
    +-- index.html
    |    
    +-- data
    |  |  
    |  \-- dataset.csv
    

    Then the code in index.html would look like

    d3.csv("data/dataset.csv", function(err, data) {
    
        if (err) console.log(err) // error messages
    
        console.log(data);   // should contain the parsed csv
    });