In the previous article, I mentioned RGB to Hex or Hex to RBG using Javascript, but in this article, I have mentioned how to convert CSV file data into JSON using Javascript, first we will read CSV file using Javascript, and then we will convert CSV into JSON.

Step 1: Read CSV file using Javascript

In first step, we will read or load a local CSV file using Javascript, here is the code for it

function processFile() {
    var fileSize = 0;
    //get file
    var theFile = document.getElementById("myFile");
    
     var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
     //check if file is CSV
     if (regex.test(theFile.value.toLowerCase())) {
     //check if browser support FileReader
        if (typeof (FileReader) != "undefined") {
        //create html5 file reader object
        var myReader = new FileReader();
        // call filereader. onload function
        myReader.onload = function(e) {
            var content = myReader.result;
          

//do something with CSV file here

          
          
        }
        //call file reader onload
        myReader.readAsText(theFile.files[0]);
        }
        else {
                alert("This browser does not support HTML5.");
            }
        
    }
    else {
                alert("Please upload a valid CSV file.");
    }
    return false;
}

Step 2: Once, we have got the CSV file in HTML 5 reader, then we can use it to loop each line of CSV and Convert it into JSON using below Javascript code

           var lines=fileContent.split("\n");

            var result = [];

            var headers=lines[0].split(",");

            for(var i=1;i<lines.length;i++){

              var obj = {};
              var currentline=lines[i].split(",");

              for(var j=0;j<headers.length;j++){
                obj[headers[j]] = currentline[j];
              }

              result.push(obj);

           }
      
          //log JSON result.
           console.log(JSON.parse(JSON.stringify(result))); //JSON

First, we will take the whole CSV file and split it into an array of lines.

Then, we take the first line, which is of headers, and split that by a comma into an array.

Then, I loop through all the remaining lines (skipping the first one) and inside, I loop through the headers and assign the values from each line to the proper objects.

Here is the complete Javascript code.

function processFile() {
    var fileSize = 0;
    //get file
    var theFile = document.getElementById("myFile");
    
     var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
     //check if file is CSV
     if (regex.test(theFile.value.toLowerCase())) {
     //check if browser support FileReader
        if (typeof (FileReader) != "undefined") {
        //create html5 file reader object
        var myReader = new FileReader();
        // call filereader. onload function
        myReader.onload = function(e) {
            var content = myReader.result;
            //split csv file using "\n" for new line ( each row)

            var lines=content.split("\n");

            var result = [];

            var headers=lines[0].split(",");

            for(var i=1;i<lines.length;i++){

              var obj = {};
              var currentline=lines[i].split(",");

              for(var j=0;j<headers.length;j++){
                obj[headers[j]] = currentline[j];
              }

              result.push(obj);

           }
      
           //return result; //JavaScript object
           console.log( JSON.parse(JSON.stringify(result))); //JSON
          
        }
        //call file reader onload
        myReader.readAsText(theFile.files[0]);
        }
        else {
                alert("This browser does not support HTML5.");
            }
        
    }
    else {
                alert("Please upload a valid CSV file.");
    }
    return false;
}

We will also use html to upload CSV file from local, which would be as below

Select a file: <input type="file" id="myFile">
<button onclick='processFile()'>Process</button>
<table id="myTable"></table>

That's it, we are done.

For demo purposes, I am using Below CSV

Id,Country,Price,OrderQuantity
1,India,10.00,4
2,Australia, 5.00,10
3,Brazil, 10.00,5
4,China,5.50,5
5,Nepal,20.20,10

And here is the output, when using the above code in JS fiddle

convert-csv-to-json-javascript

Here is the fiddle

That's it, hope you are able to read CSV and then convert CSV to JSON using the above guide.

You may also like to read:

Easy way to convert HTML to PDF using Javascript

Read JSON file with Javascript

Convert html to word with images (Using Javascript OR Using jQuery plugin)

Read CSV file in Javascript and HTML5 FileReader (Multiple ways)

Best Javascript Drag and Drop Libraries

Convert Text to HTML using Javascript

Best Javascript Charting Library

Useful Javascript Unit Testing Frameworks