I have a csv and need to convert it to json using nodejs, but parsing many things in the process to match the required fields where i need to upload the data, like hashing some info or changing the header names.
The problem I'm having is that I need to separate the column 'Name' into two different columns, one for the first name and one for the last name.
Am I having a wrong approach to the problem? Should I parse everything to match the required files like I'm trying to do or is not the best way?
CSV FILE
email,phone,Name,zipcode,country,gender,Price
[email protected],1-(650)-561-5622,Eliza Rabbit,94046,US,Female,"$15,00"
CODE
const csv=require('csvtojson');
const sha1 = require('sha1');
const csvFilePath ='filepath';
csv({
trim: true,
delimiter: [","," "],
noheaders: false,
headers: ['em', 'ph', 'fn', 'zp', 'country', 'ge', 'price'],
colParser: {
"ph":function(item){
return sha1(item);
}}})
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
});
OUTPUT
[
{
em: '[email protected]',
ph: '937a997da6b9f647b3b378ef27f91952eb09fd26',
fn: 'Eliza Rabbit',
zp: '94046',
country: 'US',
ge: 'Female',
price: '$15,00'
}
]
My first idea was to set delimiter to separate columns by commas or spaces and then define new headers manually and putting a space in the NAME column header:
noheaders: false,
headers: ['em', 'ph', 'firstName lastName', 'zp', 'country', 'ge', 'price'],
delimiter: [","," "],
Dumb, I know, of course didn't work. Just logged: 'fistName lastName': 'Eliza Rabbit'
Using
CSVParse for Node.js
. It makes life easier.CSV file
Code
Install libraries
Result