UNPKG

npm-json2csv

Version:

This module can be used to convert your JSON into CSV file effeciently.Just pass your JSON array and filepath with filename. It will extract the headers and rows by itself and could handle values with commas also.

86 lines (83 loc) 3.38 kB
function convertToCSV(objArray, options, coloumn) { if ((coloumn && !options) || (coloumn && options && coloumn.length != options.length)) { throw Error(""); } var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; var keys = []; if (options) { for (var i = 0; i < array.length; i++) { var element = Object.keys(array[i]) .map(a => ({ [a]: array[i][a] })) .sort((a, b) => (options.indexOf(Object.keys(a)[0]) + 1) - (options.indexOf(Object.keys(b)[0]) + 1)); array[i] = {} for (var j = 0; j < element.length; j++) { var key = Object.keys(element[j])[0]; array[i][key] = element[j][key]; } Object.keys(array[i]).forEach(function (key) { if (array[i][key] === null) { array[i][key] = '-'; } }) } } if (coloumn) for (var k in objArray[0]) { if (!options || options.includes(k)) { let i = options ? options.indexOf(k) : null; keys.push(coloumn && coloumn[i] ? coloumn[i] : k); } else { continue; } } for (var i = 0; i < keys.length; i++) { if (i == keys.length - 1) { str = str + keys[i] + '\r\n' } else { str = str + keys[i] + ',' } } for (var i = 0; i < array.length; i++) { var line = ''; for (var index in array[i]) { if (!options || options.includes(index)) { if (line != '') line += ',' if (array[i][index] && array[i][index].toString().includes(",") && typeof array[i][index] === 'string') { array[i][index] = "\"" + array[i][index] + "\"" } if (array[i][index] instanceof Date) { date = new Date(array[i][index]) line += formatDate(date); } else { if (array[i][index].toString().length > 11) { line += '=' + '"' + array[i][index] + '"'; } else { line += array[i][index]; } } } else { continue; } } str += line + '\r\n'; } return str; } function json2csv(arrayOfObjects, filename, options) { var fs = require('fs'); fs.writeFile(filename + ".csv", convertToCSV(arrayOfObjects, options), function (err) { if (err) console.log(err) }); } function formatAMPM(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0' + minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } function formatDate(date) { return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() + ' ' + formatAMPM(date) } var arrayOfObjects = [{ "id": 28, "Title": "Sweden" }, { "id": 56, "Title": "USA" }, { "id": 89, "Title": "England" }]; exports.json2csvfile = json2csv; exports.convertToCSV = convertToCSV;