CSV to JSON with Javascript

Few days back, while working in a project, I needed to convert csv data into json. I had either write a script or use some online tool. The quick and easy way out was to use online tool for which I had to upload data file to remote server, and that in my case was not feasible as there were some sensitive data and submitting such data to remote servers was not a good idea. So I had to find the solution in my local layer and write my own script.

Since I had to read csv data from file, I thought of server side scripting. But then I would have an overhead of setting up a server. So now I wanted a server less solution i.e. to avoid server side scripting too. And client side solution was what i had to look for. So here is the solution I got for reading data from file and converting to json with client side scripting (i.e. Javascript).


First create a file index.html and added file input field with id csvfileinput.

<input type="file" id="csvfileinput" accept=".csv"/>
 <div id="fileContents"></div> 

Here accept=”.csv” is for accepting .csv file input only.
Now we read the data from the file input with javascript FileReader Api.

$("#csvfileinput").change(function () {
var file = this.files[0];
if (file && fileExtention($(this).val()) == 'csv') {
var reader = new FileReader();
reader.onload = function (evt) {
// code to convert file data and render in json format
document.getElementById("fileContents").innerHTML = csvJSON(evt.target.result);
reader.onerror = function (evt) { 
document.getElementById("fileContents").innerHTML = "error reading file"; 
document.getElementById("fileContents").innerHTML = "Not a csv file"; 

Here we check file extension with fileExtention() method if the submitted file is .csv file or not.
csvJSON() method that takes data input and returns json string. csvJSON() method is as follows.

function csvJSON(csv){
	var lines=csv.split('\r');
	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];
	return JSON.stringify(result);

And fileExtention() method is defined as follows

function fileExtention(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];

Finally, response from method csvJSON() is rendered in #fileContents element.

<div id="fileContents"></div>

You May Also Like