diff --git a/src/lineToJson.ts b/src/lineToJson.ts index 7c93ee5..a32488d 100644 --- a/src/lineToJson.ts +++ b/src/lineToJson.ts @@ -37,10 +37,14 @@ function processRow(row: string[], conv: Converter, index): JSONResult | null { function convertRowToJson(row: string[], headRow: string[], conv: Converter): { [key: string]: any } | null { let hasValue = false; const resultRow = {}; + let len = row.length; + if (!conv.parseParam.ignoreEmpty && len > 0 && headRow.length > len) { + len = headRow.length; + } - for (let i = 0, len = row.length; i < len; i++) { - let item = row[i]; - + for (let i = 0; i < len; i++) { + let item = row[i] ?? ''; + if (conv.parseParam.ignoreEmpty && item === '') { continue; } diff --git a/test/data/dataEmptyColumns b/test/data/dataEmptyColumns new file mode 100644 index 0000000..ae8bcf1 --- /dev/null +++ b/test/data/dataEmptyColumns @@ -0,0 +1,3 @@ +col1,col2,col3 +a,b +c,d \ No newline at end of file diff --git a/test/testCSVConverter.ts b/test/testCSVConverter.ts index 3fcf92e..ce5e036 100644 --- a/test/testCSVConverter.ts +++ b/test/testCSVConverter.ts @@ -304,6 +304,20 @@ describe("CSV Converter", function () { }); }); + it("should keep empty columns when ignoreEmpty is false", function (done) { + var testData = __dirname + "/data/dataEmptyColumns"; + var rs = fs.createReadStream(testData); + var st = rs.pipe(csv({ ignoreEmpty: false })); + st.then(function (res) { + assert(res.length === 2); + assert.equal(res[0].col1, "a"); + assert.equal(res[0].col2, "b"); + assert.equal(res[0].col3, ""); + assert.equal(res[1].col3, ""); + done(); + }); + }); + it("should allow no header", function (done) { var testData = __dirname + "/data/noheadercsv"; var rs = fs.createReadStream(testData); diff --git a/v2/lineToJson.js b/v2/lineToJson.js index 659cba2..169ef72 100644 --- a/v2/lineToJson.js +++ b/v2/lineToJson.js @@ -34,11 +34,15 @@ function processRow(row, conv, index) { function convertRowToJson(row, headRow, conv) { var hasValue = false; var resultRow = {}; - for (var i = 0, len = row.length; i < len; i++) { - var item = row[i]; + var len = row.length; + if (!conv.parseParam.ignoreEmpty && len > 0 && headRow.length > len) { + len = headRow.length; + } + for (var i = 0; i < len; i++) { + var item = row[i] !== null && row[i] !== void 0 ? row[i] : ''; if (conv.parseParam.ignoreEmpty && item === '') { continue; - } + } hasValue = true; var head = headRow[i]; if (!head || head === "") {