UncleCoder.com

UncleCoder.com

Free programming examples and instructions

JQuery convert CSV file to json

Code and example for how to convert csv file to json using jQuery

by Athil


Posted on 23 May 2017 Category: jQuery Views: 1219

Edited on 13 Jun 2017



DEMO

Hi, Here I am going to show how to convert CSF file(Spreadsheet) into Excel using jQuey.

FULL CODE

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Demo for converting CVF file to json</title>
</head>
<body>
    <h1> Demo for converting CVF file to json</h1>

    <input type="file" id="fileUploadCSV"/>
    <input type="button" value="Upload csv" id="btnUpload" />
  
     <div id="DivJson"></div>
</body>
    
     <script type="text/javascript" src="js/jquery.min.js" >
    </script>
    <script>
    $(function () {
    var csv = $("#fileUploadCSV").val();
    $("#btnUpload").bind("click", function () {
    debugger;
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;//regex for Checking valid files csv of txt 
        
        
        
        if (regex.test($("#fileUploadCSV").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var rows = e.target.result.split("\r\n");

                    if(rows.length>0){
                        var first_Row_Cells = splitCSVtoCells(rows[0], ","); //Taking Headings

                        var jsonArray = new Array();
                        for(var i=1;i<rows.length;i++)
                        {
                            var cells = splitCSVtoCells(rows[i], ",");
                            
                                                    
                            var obj = {};
                            for(var j=0;j<cells.length;j++)
                            {
                                obj[first_Row_Cells[j]] = cells[j];
                            }
                            jsonArray.push(obj);
                        }
                        //Converting to json and json string to div
                        $("#DivJson").html(JSON.stringify(jsonArray));
                      
                       
                       
                       
                    }
                }
                reader.readAsText($("#fileUploadCSV")[0].files[0]);
            } 
            else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Select a valid CSV File.");
        }
    });
});
    function splitCSVtoCells(row, separator) {
    return row.split(separator);
}
</script>
</html>

Related Post

How to import CSV File to table using jQuery



Leave a Comment:


Advertisement