JSON2CSVParser.js
1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';
const JSON2CSVBase = require('./JSON2CSVBase');
class JSON2CSVParser extends JSON2CSVBase {
/**
* Main function that converts json to csv.
*
* @param {Array|Object} data Array of JSON objects to be converted to CSV
* @returns {String} The CSV formated data as a string
*/
parse(data) {
const processedData = this.preprocessData(data);
if (!this.opts.fields) {
const dataFields = processedData
.map(item => Object.keys(item))
.reduce((tempData, rows) => tempData.concat(rows), []);
this.opts.fields = dataFields
.filter((field, pos, arr) => arr.indexOf(field) == pos);
}
const header = this.opts.header ? this.getHeader() : '';
const rows = this.processData(processedData);
const csv = (this.opts.withBOM ? '\ufeff' : '')
+ header
+ ((header && rows) ? this.opts.eol : '')
+ rows;
return csv;
}
/**
* Preprocess the data according to the give opts (unwind, flatten, etc.)
and calculate the fields and field names if they are not provided.
*
* @param {Array|Object} data Array or object to be converted to CSV
*/
preprocessData(data) {
const processedData = Array.isArray(data) ? data : [data];
if (!this.opts.fields && (processedData.length === 0 || typeof processedData[0] !== 'object')) {
throw new Error('Data should not be empty or the "fields" option should be included');
}
return processedData
.map(row => this.preprocessRow(row))
.reduce((tempData, rows) => tempData.concat(rows), []);
}
/**
* Create the content row by row below the header
*
* @param {Array} data Array of JSON objects to be converted to CSV
* @returns {String} CSV string (body)
*/
processData(data) {
return data
.map(row => this.processRow(row))
.filter(row => row) // Filter empty rows
.join(this.opts.eol);
}
}
module.exports = JSON2CSVParser;