Saturday, March 23, 2019

Create CSV from Json Data


        function convertArrayOfObjectsToCSV(args) {
            var result, ctr, keys, columnDelimiter, lineDelimiter, data;

            data = args.data || null;
            if (data == null || !data.length) {
                return null;
            }

            columnDelimiter = args.columnDelimiter || ',';
            lineDelimiter = args.lineDelimiter || '\n';

            keys = Object.keys(data[0]);

            result = '';
         
            data.forEach(function(item) {
                ctr = 0;
                keys.forEach(function(key) {
                    if (ctr > 0) result += columnDelimiter;

                    result += item[key];
                    ctr++;
                });
                result += lineDelimiter;
            });

            return result;
        }




now days there are libraries exists which does this however  my company don't wanted to choose any library so like above approach

if you not restricted with adding new libraries then use CSVHelper 
https://joshclose.github.io/CsvHelper/ 

No comments:

Post a Comment