6 examples of 'json to csv node js' in JavaScript

Every line of 'json to csv node js' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
61export function convertCSVToJSON(csv, keySeparator = ',', lineSeparator = '\r\n', indent = 2) {
62 if (!csv) {
63 return '';
64 }
65 /** @type {?} */
66 const csvArray = csv.split(lineSeparator);
67 // Input CSV must have a minimum of two rows
68 if (csvArray.length < 2) {
69 return '';
70 }
71 /** @type {?} */
72 const newObjects = [];
73 // Extract object keys from header row
74 /** @type {?} */
75 const keys = csvArray[0].split(keySeparator);
76 // Iterate through array, creating one output line per object
77 for (let i = 1; i < csvArray.length; i++) {
78 /** @type {?} */
79 const newObject = {};
80 /** @type {?} */
81 const values = csvArray[i].split(keySeparator);
82 if (values.length !== keys.length) {
83 continue;
84 }
85 for (let j = 0; j < keys.length; j++) {
86 newObject[keys[j]] = values[j];
87 }
88 newObjects.push(newObject);
89 }
90 return formatJSON(newObjects, indent);
91}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

38csvStringToJson(csvString) {
39 return this.csvToJson(csvString);
40}
315function arrayToCSV(objArray) {
316 const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
317 let str = `${Object.keys(array[0]).map(value => `"${value}"`).join(",")}` + '\r\n'; // eslint-disable-line
318
319 return array.reduce((str, next) => {
320 str += `${Object.values(next).map(value => `"${value}"`).join(",")}` + '\r\n'; // eslint-disable-line
321 return str;
322 }, str);
323}
95function arrayToCSV(rows) {
96 var content = "";
97 rows.forEach(function(row, index) {
98 content += row.join(",") + "\n";
99 });
100 return content;
101}
26function CsvToJson(path) {
27 eventEmmiter.call(this);
28 let firstData = true;
29 csvtojson()
30 .fromStream(fs.createReadStream(path))
31 .on('json', json => {
32 if (firstData) {
33 firstData = !firstData;
34 this.emit('start');
35 }
36 this.emit('json', json);
37 })
38 .on('done', (error) => {
39 if (error) {
40 this.emit('error', error);
41 } else {
42 this.emit('end');
43 }
44 });
45}
30convertJsonToCsv: function convertJsonToCsv (joinedSettlementJson, keys) {
31 try {
32 return json2csv({
33 data: joinedSettlementJson,
34 fields: keys,
35 del: '',
36 doubleQuotes: '\'',
37 hasCSVColumnTitle: true
38 })
39 } catch (err) {
40 // Errors are thrown for bad options, or if the data is empty and no fields are provided.
41 // Be sure to provide fields if it is possible that your data array will be empty.
42 return err
43 }
44}

Related snippets