Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❀ đŸ’»

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to convert json to csv?

0 contributions
7 points

In this article, we're going to have a look at the problem how to convert JSON to CSV.

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

Quick overview:

// 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);
});

More detailed method description is placed below.

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. First one makes conversion of single objects. Second one converts array of objects to CSV.

1.1. Sigle object to CSV conversion example

This approach is useful when we have 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 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);

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more