JSON to CSV Converter in Javascript



Result:


How to Convert JSON to CSV using Javascript:

  • Get JSON string from user.
  • Convert string to JSON array or object.
  • Convert JSON to String using JSON.stringify() function
    Syntax: JSON.stringify(obj);
  • Call ConvertToCSV() function and pass JSON String to that function.
  • Create a Blob file and download it.

Get JSON string from user:


<textarea id="json_string" rows="5"></textarea>

Convert String to JSON:


var obj = JSON.parse(STRING);

Convert JSON to String:


var str1 = JSON.stringify(obj);

Convert JSON to CSV:


function ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
    }

    return str;
}

Create CSV file and Download it


let blob = new Blob([ConvertToCSV(str1)],{type: "octet/stream"});
url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = "result.csv";
a.click();
window.URL.revokeObjectURL(url);

Full Source Code:


<div class="form-group">
    <textarea class="form-control data" rows="10"></textarea>
</div>
<button class="btn btn-primary" onclick="format()">FORMAT</button>
<br>
<h4>Result:</h4>
<div class="result"></div>  
<style>
    .result {
        padding: 5px; margin: 5px;
        min-height: 100px;
        outline: 1px solid #ccc;
    }
</style>
<script>
    function ConvertToCSV(objArray) {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';
    
        for (var i = 0; i < array.length; i++) {
            var line = '';
            for (var index in array[i]) {
                if (line != '') line += ','
    
                line += array[i][index];
            }
    
            str += line + '\r\n';
        }
    
        return str;
    }
    
    function format() {
        var string = document.querySelector(".data").value;
        var obj = JSON.parse(string);
        var str1 = JSON.stringify(obj);
        let blob = new Blob([ConvertToCSV(str1)],{type: "octet/stream"});
        url = window.URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = url;
        a.download = "result.csv";
        a.click();
        window.URL.revokeObjectURL(url);
        document.querySelector(".result").innerText = ConvertToCSV(str1);
    }
</script>