# All files / csv2json/libs/core linesToJson.js

0% Statements 0/121
0% Branches 0/88
0% Functions 0/16
0% Lines 0/121

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

     var parserMgr = require("./parserMgr.js");
    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 || !Array.isArray(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, len = lines.length; i < len; i++) {
        rtn.push({
          err: null,
          json: {},
          index: idx++,
          row: lines[i]
        });
      }
      return rtn;
    }

    function processRows(csvRows, params, startIndex) {
      var res = [];
      for (var i = 0, len = csvRows.length; i < len; i++) {
        var r = processRow(csvRows[i], params, startIndex++);
        if (r) {
          res.push(r);
        }
      }
      return res;
    }

    function processRow(row, param, index) {
      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 (var i = 0, len = row.length; i < len; i++) {
        var convertFunc, head, item;
        item = row[i];

        if (param.ignoreEmpty && item === '') {
          continue;
        }
        hasValue = true;

        head = headRow[i];
        if (!head || head === "") {
          head = headRow[i] = "field" + (i + 1);
        }
        var convFunc = getConvFunc(head, i, param);
        if (convFunc) {
          var convRes = convFunc(item, head, resultRow,row,i);
          if (convRes !== undefined) {
            setPath(resultRow, head, convRes);
          }
        } else {
          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);
          }
        }
      }
      if (hasValue) {
        return resultRow;
      } else {
        return false;
      }
    }

    var builtInConv={
      "string":stringType,
      "number":numberType,
      "omit":function(){}
    }
    function getConvFunc(head,i,param){
      if (param._columnConv[i] !== undefined){
        return param._columnConv[i];
      }else{
        var flag=param.colParser[head];
        if (flag === undefined){
          return param._columnConv[i]=false;
        }
        if (typeof flag ==="string"){
          flag=flag.trim().toLowerCase();
          var builtInFunc=builtInConv[flag];
          if (builtInFunc){
            return param._columnConv[i]=builtInFunc;
          }else{
            return param._columnConv[i]=false;
          }
        }else if (typeof flag ==="function"){
          return param._columnConv[i]=flag;
        }else{
          return param._columnConv[i]=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];
      }

      var flag = getFlag(head, i, param);
      var str = head.replace('*flat*', '').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;
      } 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(item);
      }
      if (numReg.test(trimed)) {
        return numberType(item);
      } else if (trimed.length === 5 && trimed.toLowerCase() === "false" || trimed.length === 4 && trimed.toLowerCase() === "true") {
        return booleanType(item);
      } else if (trimed[0] === "{" && trimed[trimed.length - 1] === "}" || trimed[0] === "[" && trimed[trimed.length - 1] === "]") {
        return jsonType(item);
      } else {
        return stringType(item);
      }
    }

    function booleanType(item) {
      var trimed = item.trim();
      if (trimed.length === 5 && trimed.toLowerCase() === "false") {
        return false;
      } else {
        return true;
      }
    }

    function jsonType(item) {
      try {
        return JSON.parse(item);
      } catch (e) {
        return item;
      }
    }