csvToJson
csvToJson copied to clipboard
[BUG] TypeError: csvToJson.indexHeader is not a function
Expected Behavior
Should not throw error.
Actual Behavior
$ node test.js raw/0* 1 ↵
[ { a: 'e', b: 'f' } ]
/Users/js/code/private/csv2report/node_modules/convert-csv-to-json/index.js:42
csvToJson.indexHeader(index);
^
TypeError: csvToJson.indexHeader is not a function
at exports.indexHeader (/Users/js/code/private/csv2report/node_modules/convert-csv-to-json/index.js:42:13)
at file:///Users/js/code/private/csv2report/test.js:6:4
at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
at async DefaultModuleLoader.import (node:internal/modules/esm/loader:228:24)
at async loadESM (node:internal/process/esm_loader:40:7)
at async handleMainPromise (node:internal/modules/run_main:66:12)
Steps to Reproduce the Problem
- Prepare 2 or more csv files
- Save test.js
import csv from 'convert-csv-to-json'
for (const file of process.argv.slice(2)) {
console.log(`===${file}===`)
var json = csv
.fieldDelimiter(',')
.indexHeader(0)
.supportQuotedField(true)
.getJsonFromCsv(file)
console.log(`===${file} JSON===`)
console.log(json)
}
- Run following, replace csv files with your own
node test.js 01.csv 02.csv
- 1st file will always pass, then 2nd file will throw error
Specifications
- Version:
- "convert-csv-to-json": "^2.0.0"
- Node.js v20.4.0
PS
Seems the issue arise from csvToJson.js:
Ln27: indexHeader(indexHeader) ...
Here `indexHeader` is a class function
Ln31: this.indexHeader = indexHeader;
After 1st time `indexHeader()` is called, `this.indexHeader` changed from a function to an integer.
So happy to see this issue has already been reported. I am facing the same issue.
So happy to see this issue has already been reported. I am facing the same issue.
Luckily indexHeader is not private. My workaround is assign the number directly and ignore the function. Small draw bask is you cannot chain it, and have to assign it before calling getJsonFromCsv() etc.
import csv from 'convert-csv-to-json'
# Assign indexHeader first
csv.indexHeader = 5
# Then call ...
var json = csv
.fieldDelimiter(',')
.supportQuotedField(true)
.getJsonFromCsv(file)