-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathcsvtojson.js
10641 lines (9218 loc) · 289 KB
/
csvtojson.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
if (window){
window.csvtojson=require("./index.js");
window.csvtojson.version=require("./package.json").version;
}
},{"./index.js":2,"./package.json":130}],2:[function(require,module,exports){
module.exports = require("./libs/csv2json.js");
},{"./libs/csv2json.js":24}],3:[function(require,module,exports){
var util=require("util");
module.exports=CSVError;
function CSVError(err,index,extra){
Error.call(this,"");
this.err=err;
this.line=index;
this.extra=extra;
this.message="Error: "+err+". JSON Line number: "+index+ (extra?" near: "+extra:"");
this.name="CSV Error";
}
util.inherits(CSVError,Error);
CSVError.prototype.toString=function(){
return JSON.stringify([this.err,this.line,this.extra]);
}
CSVError.column_mismatched=function(index,extra){
return new CSVError("column_mismatched",index,extra);
}
CSVError.unclosed_quote=function(index,extra){
return new CSVError("unclosed_quote",index,extra);
}
CSVError.fromArray=function(arr){
return new CSVError(arr[0],arr[1],arr[2]);
}
},{"util":72}],4:[function(require,module,exports){
(function (process){
var util = require("util");
var Transform = require("stream").Transform;
var os = require("os");
var eol = os.EOL;
// var Processor = require("./Processor.js");
var defParam=require("./defParam");
var csvline=require("./csvline");
var fileline=require("./fileline");
var dataToCSVLine=require("./dataToCSVLine");
var fileLineToCSVLine=require("./fileLineToCSVLine");
var linesToJson=require("./linesToJson");
var CSVError=require("./CSVError");
var workerMgr=require("./workerMgr");
function Converter(params,options) {
Transform.call(this,options);
_param=defParam(params);
this._options=options || {};
this.param = _param;
this.param._options=this._options;
// this.resultObject = new Result(this);
// this.pipe(this.resultObject); // it is important to have downstream for a transform otherwise it will stuck
this.started = false;//indicate if parsing has started.
this.recordNum = 0;
this.lineNumber=0; //file line number
this._csvLineBuffer="";
this.lastIndex=0; // index in result json array
//this._pipe(this.lineParser).pipe(this.processor);
// this.initNoFork();
if (this.param.forked){
this.param.forked=false;
this.workerNum=2;
}
this.flushCb = null;
this.processEnd = false;
this.sequenceBuffer = [];
this._needJson=null;
this._needEmitResult=null;
this._needEmitFinalResult=null;
this._needEmitJson=null;
this._needPush=null;
this._needEmitCsv=null;
this._csvTransf=null;
this.finalResult=[];
// this.on("data", function() {});
this.on("error", emitDone(this));
this.on("end", emitDone(this));
this.initWorker();
process.nextTick(function(){
if (this._needEmitFinalResult === null){
this._needEmitFinalResult=this.listeners("end_parsed").length > 0
}
if (this._needEmitResult===null){
this._needEmitResult=this.listeners("record_parsed").length>0
}
if (this._needEmitJson === null){
this._needEmitJson=this.listeners("json").length>0
}
if (this._needEmitCsv === null){
this._needEmitCsv=this.listeners("csv").length>0
}
if (this._needJson === null){
this._needJson=this._needEmitJson || this._needEmitFinalResult || this._needEmitResult || this.transform || this._options.objectMode;
}
if (this._needPush === null){
this._needPush = this.listeners("data").length > 0 || this.listeners("readable").length>0
// this._needPush=false;
}
this.param._needParseJson=this._needJson || this._needPush;
}.bind(this))
return this;
}
util.inherits(Converter, Transform);
function emitDone(conv){
return function(err){
process.nextTick(function(){
conv.emit('done',err)
})
}
}
Converter.prototype._transform = function(data, encoding, cb) {
if (this.param.toArrayString && this.started === false) {
this.started = true;
if (this._needPush){
this.push("[" + eol, "utf8");
}
}
data=data.toString("utf8");
var self=this;
this.preProcessRaw(data,function(d){
if (d && d.length>0){
self.processData(self.prepareData(d), cb);
}else{
cb();
}
})
};
Converter.prototype.prepareData=function(data){
return this._csvLineBuffer+data;
}
Converter.prototype.setPartialData=function(d){
this._csvLineBuffer=d;
}
Converter.prototype.processData=function(data,cb){
var params=this.param;
var fileLines=fileline(data,this.param)
if (this.preProcessLine && typeof this.preProcessLine === "function"){
fileLines.lines=this._preProcessLines(fileLines.lines,this.lastIndex)
}
if (!params._headers){ //header is not inited. init header
this.processHead(fileLines,cb);
}else{
if (params.workerNum<=1){
var lines=fileLineToCSVLine(fileLines,params);
this.setPartialData(lines.partial);
var jsonArr=linesToJson(lines.lines,params,this.recordNum);
this.processResult(jsonArr)
this.lastIndex+=jsonArr.length;
this.recordNum+=jsonArr.length;
cb();
}else{
this.workerProcess(fileLines,cb);
}
}
}
Converter.prototype._preProcessLines=function(lines,startIdx){
var rtn=[]
for (var i=0;i<lines.length;i++){
var result=this.preProcessLine(lines[i],startIdx+i+1)
if (typeof result ==="string"){
rtn.push(result)
}else{
rtn.push(lines[i])
this.emit("error",new Error("preProcessLine should return a string but got: "+JSON.stringify(result)))
}
}
return rtn
}
Converter.prototype.initWorker=function(){
var workerNum=this.param.workerNum-1;
if (workerNum>0){
this.workerMgr=workerMgr();
this.workerMgr.initWorker(workerNum,this.param);
}
}
Converter.prototype.preRawData=function(func){
this.preProcessRaw=func;
return this;
}
Converter.prototype.preFileLine=function(func){
this.preProcessLine=func;
return this;
}
/**
* workerpRocess does not support embeded multiple lines.
*/
Converter.prototype.workerProcess=function(fileLine,cb){
var self=this;
var line=fileLine
var eol=this.getEol()
this.setPartialData(line.partial)
this.workerMgr.sendWorker(line.lines.join(eol)+eol,this.lastIndex,cb,function(results,lastIndex){
var cur=self.sequenceBuffer[0];
if (cur.idx === lastIndex){
cur.result=results;
var records=[];
while (self.sequenceBuffer[0] && self.sequenceBuffer[0].result){
var buf=self.sequenceBuffer.shift();
records=records.concat(buf.result)
}
self.processResult(records)
self.recordNum+=records.length;
}else{
for (var i=0;i<self.sequenceBuffer.length;i++){
var buf=self.sequenceBuffer[i];
if (buf.idx === lastIndex){
buf.result=results;
break;
}
}
}
// self.processResult(JSON.parse(results),function(){},true);
})
this.sequenceBuffer.push({
idx:this.lastIndex,
result:null
});
this.lastIndex+=line.lines.length;
}
Converter.prototype.processHead=function(fileLine,cb){
var params=this.param;
if (!params._headers){ //header is not inited. init header
var lines=fileLineToCSVLine(fileLine,params);
this.setPartialData(lines.partial);
if (params.noheader){
if (params.headers){
params._headers=params.headers;
}else{
params._headers=[];
}
}else{
var headerRow=lines.lines.shift();
if (params.headers){
params._headers=params.headers;
}else{
params._headers=headerRow;
}
}
if (this.param.workerNum>1){
this.workerMgr.setParams(params);
}
var res=linesToJson(lines.lines,params,0);
this.processResult(res);
this.lastIndex+=res.length;
this.recordNum+=res.length;
cb();
}else{
cb();
}
}
Converter.prototype.processResult=function(result){
for (var i=0;i<result.length;i++){
var r=result[i];
if (r.err){
this.emit("error",r.err);
}else{
this.emitResult(r);
}
}
// this.lastIndex+=result.length;
// cb();
}
Converter.prototype.emitResult=function(r){
var index=r.index;
var row=r.row;
var result=r.json;
var resultJson=null;
var resultStr=null;
if (typeof result === "string"){
resultStr=result;
}else{
resultJson=result;
}
if (resultJson===null && this._needJson){
resultJson=JSON.parse(resultStr)
if (typeof row ==="string"){
row=JSON.parse(row)
}
}
if (this.transform && typeof this.transform==="function"){
this.transform(resultJson,row,index);
resultStr=null;
}
if (this._needEmitJson){
this.emit("json",resultJson,index)
}
if (this._needEmitCsv){
if (typeof row ==="string"){
row=JSON.parse(row)
}
this.emit("csv",row,index)
}
if (this.param.constructResult && this._needEmitFinalResult){
this.finalResult.push(resultJson)
}
if (this._needEmitResult){
this.emit("record_parsed", resultJson, row, index);
}
if (this.param.toArrayString && index > 0 && this._needPush) {
this.push("," + eol);
}
if (this._options && this._options.objectMode){
this.push(resultJson);
}else{
if (this._needPush){
if (resultStr===null){
resultStr=JSON.stringify(resultJson)
}
this.push(!this.param.toArrayString?resultStr+eol:resultStr, "utf8");
}
}
}
Converter.prototype.preProcessRaw=function(data,cb){
cb(data);
}
Converter.prototype.preProcessLine=function(line,lineNumber){
return line;
}
Converter.prototype._flush = function(cb) {
var self = this;
this.flushCb=function(){
self.emit("end_parsed",self.finalResult);
if (self.workerMgr){
self.workerMgr.destroyWorker();
}
cb()
if (!self._needPush){
self.emit("end")
}
};
if (this._csvLineBuffer.length > 0) {
if (this._csvLineBuffer[this._csvLineBuffer.length-1] != this.getEol()){
this._csvLineBuffer+=this.getEol();
}
this.processData(this._csvLineBuffer,function(){
this.checkAndFlush();
}.bind(this));
} else {
this.checkAndFlush();
}
return;
};
// Converter.prototype._transformFork = function(data, encoding, cb) {
// this.child.stdin.write(data, encoding, cb);
// }
// Converter.prototype._flushFork = function(cb) {
// this.child.stdin.end();
// this.child.on("exit", cb);
// }
Converter.prototype.checkAndFlush = function() {
if (this._csvLineBuffer.length !== 0) {
this.emit("error", CSVError.unclosed_quote(this.recordNum,this._csvLineBuffer), this._csvLineBuffer);
}
if (this.param.toArrayString && this._needPush) {
this.push(eol + "]", "utf8");
}
if (this.workerMgr && this.workerMgr.isRunning()){
this.workerMgr.drain=function(){
this.flushCb();
}.bind(this);
}else{
this.flushCb();
}
}
Converter.prototype.getEol = function(data) {
if (!this.param.eol && data) {
for (var i=0;i<data.length;i++){
if (data[i]==="\r"){
if (data[i+1] === "\n"){
this.param.eol="\r\n";
}else{
this.param.eol="\r";
}
return this.param.eol;
}else if (data[i]==="\n"){
this.param.eol="\n";
return this.param.eol;
}
}
this.param.eol=eol;
}
return this.param.eol || eol;
};
Converter.prototype.fromFile = function(filePath, cb) {
var fs = require('fs');
var rs=null;
this.wrapCallback(cb, function() {
if (rs && rs.destroy){
rs.destroy();
}
});
fs.exists(filePath, function(exist) {
if (exist) {
rs = fs.createReadStream(filePath);
rs.pipe(this);
} else {
this.emit('error',new Error("File not exist"))
}
}.bind(this));
return this;
}
Converter.prototype.fromStream=function(readStream,cb){
if (cb && typeof cb ==="function"){
this.wrapCallback(cb);
}
process.nextTick(function(){
readStream.pipe(this);
}.bind(this))
return this;
}
Converter.prototype.transf=function(func){
this.transform=func;
return this;
}
Converter.prototype.fromString = function(csvString, cb) {
if (typeof csvString != "string") {
return cb(new Error("Passed CSV Data is not a string."));
}
if (cb && typeof cb === "function") {
this.wrapCallback(cb, function() {
});
}
process.nextTick(function(){
this.end(csvString)
}.bind(this))
return this;
};
Converter.prototype.wrapCallback = function(cb, clean) {
if (clean === undefined){
clean=function(){}
}
if (cb && typeof cb ==="function"){
this.once("end_parsed", function(res) {
if (!this.hasError) {
cb(null, res);
}
}.bind(this));
}
this.once("error", function(err) {
this.hasError=true;
if (cb && typeof cb ==="function"){
cb(err);
}
clean();
}.bind(this));
}
module.exports = Converter;
}).call(this,require('_process'))
},{"./CSVError":3,"./csvline":5,"./dataToCSVLine":6,"./defParam":7,"./fileLineToCSVLine":14,"./fileline":15,"./linesToJson":19,"./workerMgr":23,"_process":41,"fs":30,"os":40,"stream":59,"util":72}],5:[function(require,module,exports){
var getEol=require("./getEol");
var getDelimiter=require("./getDelimiter");
var toLines=require("./fileline");
var rowSplit=require("./rowSplit");
/**
* Convert lines to csv columns
* @param {[type]} lines [file lines]
* @param {[type]} param [Converter param]
* @return {[type]} {lines:[[col1,col2,col3...]],partial:String}
*/
module.exports=function(lines,param){
var csvLines=[];
var left="";
while (lines.length){
var line=left+lines.shift();
var row=rowSplit(line,param);
if (row.closed){
csvLines.push(row.cols);
left="";
}else{
left=line+getEol(line,param);
}
}
return {lines:csvLines,partial:left};
}
},{"./fileline":15,"./getDelimiter":16,"./getEol":17,"./rowSplit":22}],6:[function(require,module,exports){
var fileline=require("./fileline");
var csvline=require("./csvline");
/**
* Convert data chunk to csv lines with cols
* @param {[type]} data [description]
* @param {[type]} params [description]
* @return {[type]} {lines:[[col1,col2,col3]],partial:String}
*/
module.exports=function(data,params){
var line=fileline(data,params);
var lines=line.lines;
var csvLines=csvline(lines,params);
return {
lines:csvLines.lines,
partial:csvLines.partial+line.partial
}
}
},{"./csvline":5,"./fileline":15}],7:[function(require,module,exports){
(function (process){
module.exports=function(params){
var _param = {
constructResult: true, //set to false to not construct result in memory. suitable for big csv data
delimiter: ',', // change the delimiter of csv columns. It is able to use an array to specify potencial delimiters. e.g. [",","|",";"]
quote: '"', //quote for a column containing delimiter.
trim: true, //trim column's space charcters
checkType: true, //whether check column type
toArrayString: false, //stream down stringified json array instead of string of json. (useful if downstream is file writer etc)
ignoreEmpty: false, //Ignore empty value while parsing. if a value of the column is empty, it will be skipped parsing.
workerNum: getEnv("CSV_WORKER",1), //number of parallel workers. If multi-core CPU available, increase the number will get better performance for large csv data.
fork: false, //use another CPU core to convert the csv stream
noheader: false, //indicate if first line of CSV file is header or not.
headers: null, //an array of header strings. If noheader is false and headers is array, csv header will be ignored.
flatKeys: false, // Don't interpret dots and square brackets in header fields as nested object or array identifiers at all.
maxRowLength: 0, //the max character a csv row could have. 0 means infinite. If max number exceeded, parser will emit "error" of "row_exceed". if a possibly corrupted csv data provided, give it a number like 65535 so the parser wont consume memory. default: 0
checkColumn: false, //whether check column number of a row is the same as headers. If column number mismatched headers number, an error of "mismatched_column" will be emitted.. default: false
escape:'"', //escape char for quoted column
/**below are internal params */
_headerType:[],
_headerTitle:[],
_headerFlag:[],
_headers:null
};
if (!params){
params={};
}
for (var key in params) {
if (params.hasOwnProperty(key)) {
_param[key] = params[key];
}
};
return _param;
}
function getEnv(key,def){
if (process.env[key]){
return process.env[key];
}else{
return def;
}
}
}).call(this,require('_process'))
},{"_process":41}],8:[function(require,module,exports){
module.exports = [
require('./parser_array.js'),
require('./parser_json.js'),
require('./parser_omit.js'),
require('./parser_jsonarray.js'),
require("./parser_flat.js")
];
},{"./parser_array.js":9,"./parser_flat.js":10,"./parser_json.js":11,"./parser_jsonarray.js":12,"./parser_omit.js":13}],9:[function(require,module,exports){
module.exports = {
"name": "array",
"processSafe":true,
"regExp": /^\*array\*/,
"parserFunc": function parser_array(params) {
var fieldName = params.head.replace(this.regExp, '');
if (params.resultRow[fieldName] === undefined) {
params.resultRow[fieldName] = [];
}
params.resultRow[fieldName].push(params.item);
}
};
},{}],10:[function(require,module,exports){
module.exports = {
"name": "flat",
"processSafe":true,
"regExp": /^\*flat\*/,
"parserFunc": function parser_flat (params) {
var key=this.getHeadStr();
var val=params.item;
params.resultRow[key]=val;
}
};
},{}],11:[function(require,module,exports){
var arrReg = /\[([0-9]*)\]/;
function processHead(pointer, headArr, arrReg, flatKeys) {
var headStr, match, index;
while (headArr.length > 1) {
headStr = headArr.shift();
// match = headStr.match(arrReg);
match = flatKeys ? false : headStr.match(arrReg);
if (match) { //if its array, we need add an empty json object into specified index.
if (pointer[headStr.replace(match[0], '')] === undefined) {
pointer[headStr.replace(match[0], '')] = [];
}
index = match[1]; //get index where json object should stay
pointer = pointer[headStr.replace(match[0], '')];
if (index === '') { //if its dynamic array index, push to the end
index = pointer.length;
}
if (!pointer[index]) { //current index in the array is empty. we need create a new json object.
pointer[index] = {};
}
pointer = pointer[index];
} else { //not array, just normal JSON object. we get the reference of it
if (pointer[headStr] === undefined) {
pointer[headStr] = {};
}
pointer = pointer[headStr];
}
}
return pointer;
}
module.exports = {
"name": "json",
"processSafe": true,
"regExp": /^\*json\*/,
"parserFunc": function parser_json(params) {
var fieldStr = this.getHeadStr();
var headArr = (params.config && params.config.flatKeys) ? [fieldStr] : fieldStr.split('.');
var match, index, key, pointer;
//now the pointer is pointing the position to add a key/value pair.
var pointer = processHead(params.resultRow, headArr, arrReg, params.config && params.config.flatKeys);
key = headArr.shift();
match = (params.config && params.config.flatKeys) ? false : key.match(arrReg);
if (match) { // the last element is an array, we need check and treat it as an array.
try {
key = key.replace(match[0], '');
if (!pointer[key] || !(pointer[key] instanceof Array)) {
pointer[key] = [];
}
if (pointer[key]) {
index = match[1];
if (index === '') {
index = pointer[key].length;
}
pointer[key][index] = params.item;
} else {
params.resultRow[fieldStr] = params.item;
}
} catch (e) {
params.resultRow[fieldStr] = params.item;
}
} else {
if (typeof pointer=== "string"){
params.resultRow[fieldStr] = params.item;
}else{
pointer[key] = params.item;
}
}
}
};
},{}],12:[function(require,module,exports){
module.exports = {
"name": "jsonarray",
"processSafe":true,
"regExp": /^\*jsonarray\*/,
"parserFunc": function parser_jsonarray (params) {
var fieldStr = params.head.replace(this.regExp, "");
var headArr = fieldStr.split('.');
var pointer = params.resultRow;
while (headArr.length > 1) {
var headStr = headArr.shift();
if (pointer[headStr] === undefined) {
pointer[headStr] = {};
}
pointer = pointer[headStr];
}
var arrFieldName = headArr.shift();
if (pointer[arrFieldName] === undefined) {
pointer[arrFieldName] = [];
}
pointer[arrFieldName].push(params.item);
}
};
},{}],13:[function(require,module,exports){
module.exports = {
"name": "omit",
"regExp": /^\*omit\*/,
"processSafe":true,
"parserFunc": function parser_omit() {}
};
},{}],14:[function(require,module,exports){
var csvline=require("./csvline");
/**
* Convert data chunk to csv lines with cols
* @param {[type]} data [description]
* @param {[type]} params [description]
* @return {[type]} {lines:[[col1,col2,col3]],partial:String}
*/
module.exports=function(fileLine,params){
var lines=fileLine.lines;
var csvLines=csvline(lines,params);
return {
lines:csvLines.lines,
partial:csvLines.partial+fileLine.partial
}
}
},{"./csvline":5}],15:[function(require,module,exports){
var getEol=require("./getEol");
/**
* convert data chunk to file lines array
* @param {string} data data chunk as utf8 string
* @param {object} param Converter param object
* @return {Object} {lines:[line1,line2...],partial:String}
*/
module.exports=function(data,param){
var eol=getEol(data,param);
var lines= data.split(eol);
var partial=lines.pop();
return {lines:lines,partial:partial};
}
},{"./getEol":17}],16:[function(require,module,exports){
module.exports=getDelimiter;
var defaulDelimiters=[",","|","\t",";",":"];
function getDelimiter(rowStr,param) {
var checker;
if (param.delimiter==="auto"){
checker=defaulDelimiters;
}else if (param.delimiter instanceof Array){
checker=param.delimiter;
}else{
return param.delimiter;
}
var count=0;
var rtn=",";
checker.forEach(function(delim){
var delimCount=rowStr.split(delim).length;
if (delimCount>count){
rtn=delim;
count=delimCount;
}
});
return rtn;
}
},{}],17:[function(require,module,exports){
//return eol from a data chunk.
var eol=require("os").EOL;
module.exports=function(data,param){
if (!param.eol && data) {
for (var i=0;i<data.length;i++){
if (data[i]==="\r"){
if (data[i+1] === "\n"){
param.eol="\r\n";
}else{
param.eol="\r";
}
return param.eol;
}else if (data[i]==="\n"){
param.eol="\n";
return param.eol;
}
}
param.eol=eol;
}
return param.eol;
}
},{"os":40}],18:[function(require,module,exports){
module.exports=constructor;
module.exports.Converter = require("./Converter.js");
// module.exports.Parser = require("./parser.js");
// module.exports.parserMgr = require("./parserMgr.js");
function constructor(param,options){
return new module.exports.Converter(param,options)
}
},{"./Converter.js":4}],19:[function(require,module,exports){
var parserMgr = require("./parserMgr.js");
var Parser = require("./parser");
var CSVError = require("./CSVError");
var numReg = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
/**
* Convert lines of csv array into json
* @param {[type]} lines [[col1,col2,col3]]
* @param {[type]} params Converter params with _headers field populated
* @param {[type]} idx start pos of the lines
* @return {[type]} [{err:null,json:obj,index:line,row:[csv row]}]
*/
module.exports = function (lines, params, idx) {
if (params._needParseJson) {
if (!params._headers) {
params._headers = [];
}
if (!params.parseRules) {
var row = params._headers;
params.parseRules = parserMgr.initParsers(row, params);
}
return processRows(lines, params, idx);
} else {
return justReturnRows(lines, params, idx);
}
}
function justReturnRows(lines, params, idx) {
var rtn = [];
for (var i = 0; i < lines.length; i++) {
rtn.push({
err: null,
json: {},
index: idx++,
row: lines[i]
})
}
return rtn;
}
function processRows(csvRows, params, startIndex) {
var count = csvRows.length;
var res = [];
for (var i = 0; i < csvRows.length; i++) {
var r = processRow(csvRows[i], params, startIndex++);
if (r) {
res.push(r);
}
}
return res;
}
function getConstParser(number, param) {
var inst = new Parser("field" + number, /.*/, function (params) {
var name = this.getName();
params.resultRow[name] = params.item;
}, true);
inst.setParam(param);
return inst;
}
function processRow(row, param, index) {
var i, item, parser, head;
var parseRules = param.parseRules;
if (param.checkColumn && row.length != parseRules.length) {
return {
err: CSVError.column_mismatched(index)
}
}
var headRow = param._headers;
var resultRow = convertRowToJson(row, headRow, param);
if (resultRow) {
return {
json: resultRow,
index: index,
row: row
};
} else {
return null;
}
}
function convertRowToJson(row, headRow, param) {
var hasValue = false;
var resultRow = {};
for (i = 0; i < row.length; i++) {
item = row[i];
if (param.ignoreEmpty && item === '') {
continue;
}
hasValue = true;
// parser = parseRules[i];
// if (!parser) {
// parser = parseRules[i] = getConstParser(i + 1, param);
// }
head = headRow[i];
if (!head || head === "") {
head = headRow[i] = "field" + (i + 1);
// parser.initHead(head);
}
var flag = getFlag(head, i, param)
if (flag === 'omit') {
continue
}
if (param.checkType) {
convertFunc = checkType(item, head, i, param)
item = convertFunc(item)
}
var title = getTitle(head, i, param)
if (flag === 'flat' || param.flatKeys) {
resultRow[title] = item
} else {
setPath(resultRow, title, item)
}
// _.set(resultRow,head,item)
// parser.parse({
// head: head,
// item: item,
// itemIndex: i,
// rawRow: row,
// resultRow: resultRow,
// rowIndex: index,
// config: param || {}
// });
}
if (hasValue) {
return resultRow
} else {
return false
}
}
function setPath(json, path, value) {
var _set = require('lodash/set')
var pathArr = path.split('.')
if (pathArr.length === 1) {
json[path] = value;
} else {
_set(json, path, value)
}
}
function getFlag(head, i, param) {
if (typeof param._headerFlag[i] === "string") {
return param._headerFlag[i]
} else {
if (head.indexOf('*omit*') > -1) {
return param._headerFlag[i] = 'omit'
} else if (head.indexOf('*flat*') > -1) {
return param._headerFlag[i] = 'flat'
} else {
return param._headerFlag[i] = ''
}
}
}
function getTitle(head, i, param) {
if (param._headerTitle[i]) {
return param._headerTitle[i]
} else {
var flag = getFlag(head, i, param)
var str = head.replace(flag, '')
str = str.replace('string#!', '').replace('number#!', '')
return param._headerTitle[i] = str
}
}
function checkType(item, head, headIdx, param) {
if (param._headerType[headIdx]) {
return param._headerType[headIdx]
} else {
if (head.indexOf('number#!') > -1) {
return param._headerType[headIdx] = numberType
} else if (head.indexOf('string#!') > -1) {
return param._headerType[headIdx] = stringType
} else if (param.checkType) {
return param._headerType[headIdx] = dynamicType(item)
} else {
return param._headerType[headIdx] = stringType
}
}
}
function numberType(item) {
var rtn = parseFloat(item)
if (isNaN(rtn)) {
return item;
}
return rtn;
}
function stringType(item) {
return item.toString();
}
function dynamicType(item) {
var trimed = item.trim();
if (trimed === "") {
return stringType;
}
if (numReg.test(trimed)) {
return numberType
} else if (trimed.length === 5 && trimed.toLowerCase() === "false" || trimed.length === 4 && trimed.toLowerCase() === "true") {
return booleanType;
} else if (trimed[0] === "{" && trimed[trimed.length - 1] === "}" || trimed[0] === "[" && trimed[trimed.length - 1] === "]") {
return jsonType;
} else {
return stringType;
}
}
function booleanType(item) {
var trimed = item.trim();
if (trimed.length === 5 && trimed.toLowerCase() === "false") {
return false;
} else {
return true;
}
}