I have a csv
file in which a row sometimes has two values for a column. Currently I m trying to split using ,
but is not working as expected. Can someone throw light on how to achieve the expected output. I do not want to use any npm
library.
//users.csv
name,age,hobbies
james,20,"reading,playing"
marie,18,singing
peter,19,watching movies
//index.js
const fs = require('fs');
const {promisify} = require("util");
const readFile = promisify(fs.readFile)
const readSheet = async () =>{
const result = await readFile("./users.csv", "utf-8");
const csv = result.split("\n").map(ele=>ele.split(","))
let keys = csv.slice(0,1)[0];
const values = csv.slice(1)
keys.map(keys=>keys.split(''))
let usersArr = [];
for(let i = 0;i<values.length;i++){
let usersObj = {};
keys.forEach((key,j)=>usersObj[key] = values[i][j])
usersArr.push(usersObj)
}
return usersArr
}
//current output
[ { name: 'james', age: '20', hobbies: '"reading' },
{ name: 'marie', age: '18', hobbies: 'singing' },
{ name: 'peter', age: '19', hobbies: 'watching movies' } ]
//expected output object
[
{
"name": "james",
"age": 20,
"hobbies": ["reading","playing"]
},
{
"name": "marie",
"age": 18,
"hobbies": ["singing"]
},
{
"name": "peter",
"age": 19,
"hobbies": ["watching movies"]
}
]
You could use the csv function described in this blog article: https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
Afterwards convert the arrays to objects:
Afterwards just split the hobbies column in the array by comma: