Pages

2017/03/26

How to parse CSV string using Papa Parse

This is an example of how to form a CSV string and parse it using Papa Parse.

Code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
    <!-- Load papaparse.js -->
    <script src="papaparse.min.js"></script>
</head>
<body>
    <br><br><br>
    <div class="container">
        <div id="chart"></div>
    </div>

    <script>
        //Parse the data.
        function parseData() {
            csv = "Date,Time,Station_id,Ambient Humidity,Ambient Temperature,Light,Probe Temperature,DI1,DI2" + "\n" +
                  "2017-03-23,16:37:38,1,70.10,22.10,859,22.50,0,0" + "\n" +
                  "2017-03-23,16:42:51,1,70.50,22.30,820,21.88,0,0" + "\n" +
                  "2017-03-23,16:32:25,1,69.90,22.10,848,22.38,0,0" + "\n" +
                  "2017-03-23,16:27:12,1,70.30,22.10,866,22.25,0,0" + "\n" +
                  "2017-03-23,14:21:11,1,71.40,22.60,577,22.38,0,0" + "\n" +
                  "2017-03-23,13:02:45,1,73.10,22.60,558,22.31,0,0" + "\n" +
                  "2017-03-23,13:34:02,1,74.00,22.60,577,22.38,0,0" + "\n" +
                  "2017-03-23,12:20:59,1,75.20,22.50,435,22.25,0,0" + "\n" +
                  "2017-03-23,11:49:39,1,76.00,22.60,572,22.31,0,0";
            var data = Papa.parse(csv);
            console.log(data);
        }

        parseData();

    </script>

</body>
</html>

Note that "\n" is needed at the end of each line to indicate the end of a row of data in the CSV string; without it, the whole CSV string will be treated as one line and you will have one long row of data...

Once the code is done, save it as index.html (or other filename name that ends with ".html"), then double click on the saved file to launch a browser to execute it.

Result

At first glance, there's nothing to see.


If Google Chrome is used, enable the Developer Tools under More Tools / Developer Tool.


Under Console, there is an array that contains 10 rows of data.


Click on data, then on individual Array to see the data.


The CSV string is now successfully parsed and put in an array.

References:

Parsing a Local CSV File with JavaScript and Papa Parse
http://www.joyofdata.de/blog/parsing-local-csv-file-with-javascript-papa-parse/

How to Create Website Graphs from CSV Files with c3.js and PapaParse
https://youtu.be/1OK4TJfCzdY

No comments:

Post a Comment