Languages
[Edit]
EN

JavaScript - convert json to csv

7 points
Created by:
sienko
743

In this article, we would like to show you how to convert JSON to CSV using JavaScript.

There is no built-in conversion method so it is necessary to write own one method.

Quick solution:

// required: https://requirejs.org/docs/release/2.3.6/minified/require.js

require(['https://cdn.jsdelivr.net/npm/json2csv@4.2.1'], function(json2csv) {
    var parser = new json2csv.Parser();

    var data = [
        { "id": 5,  "name": "John",  "age": 25 },
        { "id": 21, "name": "Denis", "age": 34 },
        { "id": 59, "name": "Chris", "age": 17 }
    ];
    var csv = parser.parse(data);

    console.log(csv);
});

 

1. json2csv library usage in web browser example

This section shows how to convert json to csv with extrenal library in web browser. json2csv library requires to be loaded require library.

json2csv library on GitHub: https://github.com/zemirco/json2csv

json2csv library on npmjs: https://www.npmjs.com/package/json2csv

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
</head>
<body>
  <script>
    require(['https://cdn.jsdelivr.net/npm/json2csv@4.2.1'], function(json2csv) {
		var parser = new json2csv.Parser();
    
		var json = '' +
            '[' +
            '    { "id": 5,  "name": "John",  "age": 25 },' +
            '    { "id": 21, "name": "Denis", "age": 34 },' +
            '    { "id": 59, "name": "Chris", "age": 17 }' +
            ']';
		
		try {
			var data = JSON.parse(json);
			var csv = parser.parse(data);
		  
			console.log(csv);
		} catch (e) {
			console.error(e);
		}
    });
  </script>
</body>
</html>

2. Custom function examples

In this section, two versions of JSON to CSV methods are presented. The first one makes the conversion of single objects. The second one converts an array of objects to CSV.

1.1. Sigle object to CSV conversion example

This approach is useful when we have a simple object and we want to convert it to CSV.

// ONLINE-RUNNER:browser;

function escapeValue(value) {
    var result = '';
    var escape = false;

    for(var i = 0; i < value.length; ++i) {
        var entry = value[i];
        
        result += entry;

        switch(entry) {
            case '"': result += '"';
            case ',': escape = true;
        }
    }

    if(escape)
        return '"' + result + '"';

    return result;
}

function createCSV(object) {
    var head = '';
  	
  	for(var column in object) {
      	if(object.hasOwnProperty(column)) {
        	if(head)
        		head += ',';

          	head += escapeValue(column.toString());
      	}
    }

  	var body = '';

  	for(var column in object) {
      	if(object.hasOwnProperty(column)) {
        	if(body)
        		body += ',';
      
          	var value = object[column];
          
            if(value == null)
                continue;
          
          	body += escapeValue(value.toString());
      	}
    }

    return head + '\n' + body;
}

// Example:

var json = '{ "id": 5,  "name": "John",  "age": 25 }';

var object = JSON.parse(json);
var csv = createCSV(object);

console.log(csv);

2.2. Array of objects to CSV conversion example

This approach is useful when we have an array of simple objects and we want to convert it to CSV.

// ONLINE-RUNNER:browser;

function detectColumns(array) {
    var guardian = { };
    var columns = [ ];

    for(var i = 0; i < array.length; ++i) {
        var entry = array[i];

        for(var key in entry) {
            if(key in guardian) {
                continue;
            }

          	if(entry.hasOwnProperty(key)) {
                guardian[key] = true;
                columns.push(key);
            }
        }
    }

    return columns;
}

function escapeValue(value) {
    var result = '';
    var escape = false;

    for(var i = 0; i < value.length; ++i) {
        var entry = value[i];
        
        result += entry;

        switch(entry) {
            case '"': result += '"';
            case ',': escape = true;
        }
    }

    if(escape)
        return '"' + result + '"';

    return result;
}

function createCSV(array) {
    var csv = '';

    var columns = detectColumns(array);
  
  	for(var j = 0; j < columns.length; ++j) {
      	if(j > 0)
        	csv += ',';
      
      	var column = columns[j];

      	if(column == null)
          	continue;

      	csv += escapeValue(column.toString());
    }

  	csv += '\n';

    for(var i = 0; i < array.length; ++i) {
        var entry = array[i];

        for(var j = 0; j < columns.length; ++j) {
            if(j > 0)
                csv += ',';

            var column = columns[j];
            var value = entry[column];

            if(value == null)
                continue;

            csv += escapeValue(value.toString());
        }

        csv += '\n';
    }

    return csv;
}

// Example:

var json = '' +
    '[' +
    '    { "id": 5,  "name": "John",  "age": 25 },' +
    '    { "id": 21, "name": "Denis", "age": 34 },' +
    '    { "id": 59, "name": "Chris", "age": 17 }' +
    ']';

var array = JSON.parse(json);
var csv = createCSV(array);

console.log(csv);

Alternative titles

  1. JavaScript - how to convert json to csv?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - JSON

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join