Skip to main content

Convert CSV Data to JSON using JavaScript with Example

In our previous tutorial, we have explained how to detect DOM changes with JavaScript. In this tutorial, you will learn in easy steps to convert CSV data to JSON using JavaScript with live example.

CSV (comma-separated-values) is a popular file format to store tabular data for further use. It’s very lightweight and easy to parse into different file formats like XML, JSON etc. to use further according to requirement.

So if you’re looking for solution to parse or convert CSV file data into JSON format using JavaScript, you’re here at right place. In comparison with server side CSV data parsing, parsing of CSV data is fast using JavaScript.

Also, read:

So let’s create example to convert CSV data to JSON using JavaScript. The file structure of this example is following.

  • index.php
  • convert.js

Step1: Create CSV Convert Form HTML

As we will cover this tutorial with live example, so in index.php file, we will create HTML Form with textarea to enter CSV data and display convert JSON in another textarea.

<div class="container">
	<h2>Example: Convert CSV to JSON using JavaScript</h2>	
	<div class="form-group">
		<label for="csvData">Paste CSV Data:</label>
		<textarea id="csvData" class="form-control" rows="6"></textarea>
	</div>
	<div class="form-group">
		<label for="jsonData">JSON Data Output:</label>
		<textarea id="jsonData" class="form-control" rows="6"></textarea>
	</div>    
    <button id="convertCSV" class="btn btn-success">Convert to JSON</button>    
</div>

Step2: Convert CSV Data to JSON

Now in convert.js file, we will handle functionality to convert CSV data to JSON. We will call function CSVToJSON() on convert button click and pass CSV data to convert and display converted data into another textarea.

$( document ).ready(function() {
	$("#convertCSV").click(function() {
		var csvData = $("#csvData").val();
		var jsonData = CSVToJSON(csvData);
		$("#jsonData").val(jsonData);
	});
});

In function CSVToJSON(), we will call function CSVToArray() to store CSV data into an array and then handle functionality to convert data into JSON format and return.

function CSVToJSON(csvData) {
    var data = CSVToArray(csvData);
    var objData = [];
    for (var i = 1; i < data.length; i++) {
        objData[i - 1] = {};
        for (var k = 0; k < data[0].length && k < data[i].length; k++) {
            var key = data[0][k];
            objData[i - 1][key] = data[i][k]
        }
    }
    var jsonData = JSON.stringify(objData);
    jsonData = jsonData.replace(/},/g, "},\r\n");
    return jsonData;
}

We will use function CSVToArray() to convert and store CSV data into array for further processing.

function CSVToArray(csvData, delimiter) {
    delimiter = (delimiter || ",");
     var pattern = new RegExp((
    "(\\" + delimiter + "|\\r?\\n|\\r|^)" +
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    "([^\"\\" + delimiter + "\\r\\n]*))"), "gi");
    var data = [[]];
    var matches = null;
    while (matches = pattern.exec(csvData)) {
        var matchedDelimiter = matches[1];
        if (matchedDelimiter.length && (matchedDelimiter != delimiter)) {
            data.push([]);
        }
        if (matches[2]) {
            var matchedDelimiter = matches[2].replace(
            new RegExp("\"\"", "g"), "\"");
        } else {
            var matchedDelimiter = matches[3];
        }
        data[data.length - 1].push(matchedDelimiter);
    }
    return (data);
}

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download