1

my csv file is like this

 $(function () {
                var csv = $("#fileUpload").val();
          
                $("#upload").bind("click", function () {
                    var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
                    if (regex.test($("#fileUpload").val().toLowerCase())) {
                        if (typeof (FileReader) != "undefined") {
                            var reader = new FileReader();
                            reader.onload = function (e) {
                                var table = $("<table />");
                                var rows = e.target.result.split("\n");
                                for (var i = 0; i < rows.length; i++) {
                                    var row = $("<tr />");
                                    var cells = rows[i].split(",");
                                    for (var j = 0; j < cells.length; j++) {
                                        var cell = $("<td />");
                                        cell.html(cells[j]);
                                        row.append(cell);
                                    }
                                    table.append(row);
                                }
                                $("#dvCSV").html('');
                                $("#dvCSV").append(table);
                            }
                            reader.readAsText($("#fileUpload")[0].files[0]);
                        } else {
                            alert("This browser does not support HTML5.");
                        }
                    } else {
                        alert("Please upload a valid CSV file.");
                    }
                });
               
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
   <input type="file" id="fileUpload" name="fileUpload" />
   <input type="button" id="upload" value="Upload" name="upload"/>
   <hr />
   <div id="dvCSV"></div>

In the above code i need to convert uploaded csv file to json format using jquery.how to do this? and created json format should be downloaded as json file.please help me how to do this

7
  • 1
    Can you post the JSON format you want for your file and a csv example file, pls ? Commented Mar 10, 2016 at 7:25
  • what @ADreNaLiNe-DJ said... csv does not have a json format... so in a sense you would just send it as text. unless you want it to conform to something.... which i would struggle to understand how you are going to represent in json, i mean why not just send as text... as its more powerful as a csv format on the server side anyway... as there are usually built in classes to handle csv's Commented Mar 10, 2016 at 7:28
  • I need output like this [ { "studentid":1001, "student_firstname":"harshitha", "student_middlename":"chowdry", "student_lastname":"pai" } ] Commented Mar 10, 2016 at 8:04
  • student records will be in excel sheet so me want to convert it into json format Commented Mar 10, 2016 at 8:06
  • Please post your csv file as text instead of image. Commented Mar 10, 2016 at 8:40

1 Answer 1

1

Here is the function you want:

$(function () {
    var csv = $("#fileUpload").val();

    $("#upload").bind("click", function () {
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").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 firstRowCells = GetCSVCells(rows[0], ",");

                        var dataArray = new Array();
                        for(var i=1;i<rows.length;i++)
                        {
                            var cells = GetCSVCells(rows[i], ",");
                            var obj = {};
                            for(var j=0;j<cells.length;j++)
                            {
                                obj[firstRowCells[j]] = cells[j];
                            }
                            dataArray.push(obj);
                        }

                        $("#dvCSV").html('');
                        $("#dvCSV").append(JSON.stringify(dataArray));
                    }
                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid CSV file.");
        }
    });
});

function GetCSVCells(row, separator){
    return row.split(separator);
}

It converts the CSV content to an array of objects in which properties are read from the first line (header line) and then it is "converted" to a JSON string.

Sign up to request clarification or add additional context in comments.

3 Comments

Me tried your code the result was like this. why again student id is displaying??? here there is no option to upload csv or any other file format other than image .. how i upload my csv file?[{"studentid":"fghfghfg","student_firstname":"harshitha","student_middlename":"chowdry","student_lastname":"pai"},{"studentid":""}]
You have an empty line at the end of your file. So, you can remove it from your csv file, or you add a test the first for loopto check if line is not empty.
thanks i did minor changes in ur code .. Now its working. Thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.