-
Notifications
You must be signed in to change notification settings - Fork 31
/
Parser.js
72 lines (72 loc) · 2.31 KB
/
Parser.js
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
67
68
69
70
71
72
// packages/plainjs/src/Parser.ts
import JSON2CSVBase from "./BaseParser.js";
import { flattenReducer, fastJoin } from "./utils.js";
var JSON2CSVParser = class extends JSON2CSVBase {
constructor(opts) {
super(opts);
}
/**
* 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 preprocessedData = this.preprocessData(data);
this.opts.fields = this.opts.fields || this.preprocessFieldsInfo(
preprocessedData.reduce((fields, item) => {
Object.keys(item).forEach((field) => {
if (!fields.includes(field)) {
fields.push(field);
}
});
return fields;
}, []),
this.opts.defaultValue
);
const header = this.opts.header ? this.getHeader() : "";
const rows = this.processData(preprocessedData);
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) {
if (data === void 0 || data === null || processedData.length === 0) {
throw new Error(
'Data should not be empty or the "fields" option should be included'
);
}
if (typeof processedData[0] !== "object") {
throw new Error(
'Data items should be objects or the "fields" option should be included'
);
}
}
if (this.opts.transforms.length === 0)
return processedData;
return processedData.map((row) => this.preprocessRow(row)).reduce(flattenReducer, []);
}
/**
* 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 fastJoin(
data.map((row) => this.processRow(row)).filter((row) => row),
// Filter empty rows
this.opts.eol
);
}
};
export {
JSON2CSVParser as default
};