forked from pradeep-mishra/csvjson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
439 lines (373 loc) · 12.3 KB
/
index.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
module.exports = {
toObject : toObject,
toArray : toArray,
toColumnArray : toColumnArray,
toSchemaObject : toSchemaObject,
toCSV : toCSV
}
function toColumnArray(data, opts){
opts = opts || { };
var delimiter = (opts.delimiter || ',');
var quote = _getQuote(opts.quote);
var content = data;
var headers = null;
if(typeof(content) !== "string"){
throw new Error("Invalid input, input data should be a string");
}
content = content.split(/[\n\r]+/ig);
if(typeof(opts.headers) === "string"){
headers = opts.headers.split(/[\n\r]+/ig);
headers = quote ?
_convertArray(headers.shift(), delimiter, quote) :
headers.shift().split(delimiter);
}else{
headers = quote ?
_convertArray(content.shift(), delimiter, quote) :
content.shift().split(delimiter);
}
var hashData = { };
headers.forEach(function(item){
hashData[item] = [];
});
content.forEach(function(item){
if(item){
item = quote ?
_convertArray(item, delimiter, quote) :
item.split(delimiter);
item.forEach(function(val, index){
hashData[headers[index]].push(_trimQuote(val));
});
}
});
return hashData;
}
function toObject(data, opts){
opts = opts || { };
var delimiter = (opts.delimiter || ',');
var quote = _getQuote(opts.quote);
var content = data;
var headers = null;
if(typeof(content) !== "string"){
throw new Error("Invalid input, input data should be a string");
}
content = content.split(/[\n\r]+/ig);
if(typeof(opts.headers) === "string"){
headers = opts.headers.split(/[\n\r]+/ig);
headers = quote ?
_convertArray(headers.shift(), delimiter, quote) :
headers.shift().split(delimiter);
}else{
headers = quote ?
_convertArray(content.shift(), delimiter, quote) :
content.shift().split(delimiter);
}
var hashData = [ ];
content.forEach(function(item){
if(item){
item = quote ?
_convertArray(item, delimiter, quote) :
item.split(delimiter);
var hashItem = { };
headers.forEach(function(headerItem, index){
hashItem[headerItem] = _trimQuote(item[index]);
});
hashData.push(hashItem);
}
});
return hashData;
}
function toSchemaObject(data, opts){
opts = opts || { };
var delimiter = (opts.delimiter || ',');
var quote = _getQuote(opts.quote);
var content = data;
var headers = null;
if(typeof(content) !== "string"){
throw new Error("Invalid input, input should be a string");
}
content = content.split(/[\n\r]+/ig);
if(typeof(opts.headers) === "string"){
headers = opts.headers.split(/[\n\r]+/ig);
headers = quote ?
_convertArray(headers.shift(), delimiter, quote) :
headers.shift().split(delimiter);
}else{
headers = quote ?
_convertArray(content.shift(), delimiter, quote) :
content.shift().split(delimiter);
}
var hashData = [ ];
content.forEach(function(item){
if(item){
item = quote ?
_convertArray(item, delimiter, quote) :
item.split(delimiter);
var schemaObject = {};
item.forEach(function(val, index){
_putDataInSchema(headers[index], val, schemaObject , delimiter, quote);
});
hashData.push(schemaObject);
}
});
return hashData;
}
function toArray(data, opts){
opts = opts || { };
var delimiter = (opts.delimiter || ',');
var quote = _getQuote(opts.quote);
var content = data;
if(typeof(content) !== "string"){
throw new Error("Invalid input, input data should be a string");
}
content = content.split(/[\n\r]+/ig);
var arrayData = [ ];
content.forEach(function(item){
if(item){
item = quote ?
_convertArray(item, delimiter, quote) :
item.split(delimiter);
item = item.map(function(cItem){
return _trimQuote(cItem);
});
arrayData.push(item);
}
});
return arrayData;
}
function _getQuote(q){
if(typeof(q) === "string"){
return q;
}else if(q === true){
return '"';
}
return null;
}
function _dataType(arg) {
if (arg === null) {
return 'null';
}
else if (arg && (arg.nodeType === 1 || arg.nodeType === 9)) {
return 'element';
}
var type = (Object.prototype.toString.call(arg)).match(/\[object (.*?)\]/)[1].toLowerCase();
if (type === 'number') {
if (isNaN(arg)) {
return 'nan';
}
if (!isFinite(arg)) {
return 'infinity';
}
}
return type;
}
function toCSV(data, opts){
opts = (opts || { });
opts.delimiter = (opts.delimiter || ',');
opts.wrap = (opts.wrap || '');
opts.arrayDenote = (opts.arrayDenote && String(opts.arrayDenote).trim() ? opts.arrayDenote : '[]');
opts.objectDenote = (opts.objectDenote && String(opts.objectDenote).trim() ? opts.objectDenote : '.');
opts.detailedOutput = (typeof(opts.detailedOutput) !== "boolean" ? true : opts.detailedOutput);
opts.headers = String(opts.headers).toLowerCase();
var csvJSON = { };
var csvData = "";
if(!opts.headers.match(/none|full|relative|key/)){
opts.headers = 'full';
}else{
opts.headers = opts.headers.match(/none|full|relative|key/)[0];
}
if(opts.wrap === true){
opts.wrap = '"';
}
if(typeof(data) === "string"){
data = JSON.parse(data);
}
_toCsv(data, csvJSON, "", 0, opts);
var headers = _getHeaders(opts.headers, csvJSON, opts);
if(headers){
if(opts.wrap){
headers = headers.map(function(item){
return opts.wrap + item + opts.wrap;
});
}
csvData = headers.join(opts.delimiter);
}
var bigArrayLen = _getBigArrayLength(csvJSON);
var keys = Object.keys(csvJSON);
var row = [ ];
var replaceNewLinePattern = /\n|\r/g;
if(!opts.wrap){
replaceNewLinePattern = new RegExp('\n|\r|' + opts.delimiter, 'g');
}
for(var i = 0; i < bigArrayLen; i++){
row = [ ];
for(var j = 0; j < keys.length; j++){
if(csvJSON[keys[j]][i]){
csvJSON[keys[j]][i] = csvJSON[keys[j]][i].replace(replaceNewLinePattern, '\t');
if(opts.wrap){
csvJSON[keys[j]][i] = opts.wrap + csvJSON[keys[j]][i] + opts.wrap;
}
row[row.length] = csvJSON[keys[j]][i];
}else{
row[row.length] = "";
}
}
csvData += '\n' + row.join(opts.delimiter);
}
return csvData;
}
function _toCsv(data, table, parent, row, opt){
if(_dataType(data) === 'undefined'){
return _putData('', table, parent, row, opt);
}else if(_dataType(data) === 'null'){
return _putData('null', table, parent, row, opt);
}else if(Array.isArray(data)){
return _arrayToCsv(data, table, parent, row, opt);
}else if(typeof(data) === "object"){
return _objectToCsv(data, table, parent, row, opt);
}else{
return _putData(String(data), table, parent, row, opt);
}
}
function _putData(data, table, parent, row, opt){
if(!table || !table[parent]){
table[parent] = [ ];
}
if(row < table[parent].length){
row = table[parent].length;
}
table[parent][row] = data;
return table;
}
function _arrayToCsv(data, table, parent, row, opt){
if(_doesNotContainsObjectAndArray(data)){
return _putData(data.join(';'), table, parent + opt.arrayDenote, row, opt);
}
data.forEach(function(item, index){
return _toCsv(item, table, parent + opt.arrayDenote, index, opt);
});
}
function _doesNotContainsObjectAndArray(array){
return array.every(function(item){
var datatype = _dataType(item);
if(!datatype.match(/array|object/)){
return true;
}
return false;
});
}
function _objectToCsv(data, table, parent, row, opt){
Object.keys(data).forEach(function(item){
return _toCsv(data[item], table, parent + opt.objectDenote + item, row, opt);
});
}
function _getHeaders(headerType, table, opt){
var keyMatchPattern = /([^\[\]\.]+)$/;
var relativeMatchPattern = /\[\]\.?([^\[\]]+)$/;
switch(headerType){
case "none":
return null;
case "full":
return Object.keys(table);
case "key":
return Object.keys(table).map(function(header){
var head = header.match(keyMatchPattern);
if(head && head.length === 2){
return head[1];
}
return header;
});
case "relative":
return Object.keys(table).map(function(header){
var head = header.match(relativeMatchPattern);
if(head && head.length === 2){
return head[1];
}
return header;
});
}
}
function _getBigArrayLength(table){
var len = 0;
Object.keys(table).forEach(function(item){
if(Array.isArray(table[item]) && table[item].length > len){
len = table[item].length;
}
});
return len;
}
function _putDataInSchema(header, item, schema, delimiter, quote){
var match = header.match(/\[*[\d]\]\.(\w+)|\.|\[\]|\[(.)\]|-|\+/ig);
var headerName, currentPoint;
if(match){
var testMatch = match[0];
if(match.indexOf('-') !== -1){
return true;
}else if(match.indexOf('.') !== -1){
var headParts = header.split('.');
currentPoint = headParts.shift();
schema[currentPoint] = schema[currentPoint] || {};
_putDataInSchema(headParts.join('.'), item, schema[currentPoint], delimiter, quote);
}else if(match.indexOf('[]') !== -1){
headerName = header.replace(/\[\]/ig,'');
if(!schema[headerName]){
schema[headerName] = [];
}
schema[headerName].push(item);
}else if(/\[*[\d]\]\.(\w+)/.test(testMatch)){
headerName = header.split('[').shift();
var index = parseInt(testMatch.match(/\[(.)\]/).pop(),10);
currentPoint = header.split('.').pop();
schema[headerName] = schema[headerName] || [];
schema[headerName][index] = schema[headerName][index] || {};
schema[headerName][index][currentPoint] = item;
}else if(/\[(.)\]/.test(testMatch)){
var delimiter = testMatch.match(/\[(.)\]/).pop();
headerName = header.replace(/\[(.)\]/ig,'');
schema[headerName] = _convertArray(item, delimiter, quote);
}else if(match.indexOf('+') !== -1){
headerName = header.replace(/\+/ig,"");
schema[headerName] = Number(item);
}
}else{
schema[header] = _trimQuote(item);
}
return schema ;
}
function _trimQuote(str){
if(str){
return String(str).trim().replace(/^["|'](.*)["|']$/, '$1');
}
return "";
}
function _convertArray(str, delimiter, quote) {
if(quote && str.indexOf(quote) !== -1){
return _csvToArray(str, delimiter, quote);
}
var output = [];
var arr = str.split(delimiter);
arr.forEach(function(val) {
var trimmed = val.trim();
output.push(trimmed);
});
return output;
}
function _csvToArray(text, delimit, quote) {
delimit = delimit || ",";
quote = quote || '"';
var value = new RegExp("(?!\\s*$)\\s*(?:" + quote + "([^" + quote + "\\\\]*(?:\\\\[\\S\\s][^" + quote + "\\\\]*)*)" + quote + "|([^" + delimit + quote + "\\s\\\\]*(?:\\s+[^" + delimit + quote + "\\s\\\\]+)*))\\s*(?:" + delimit + "|$)", "g");
var a = [ ];
text.replace(value,
function(m0, m1, m2) {
if(m1 !== undefined){
a.push(m1.replace(/\\'/g, "'"));
}else if(m2 !== undefined){
a.push(m2);
}
return '';
}
);
if (/,\s*$/.test(text)){
a.push('');
}
return a;
}