I have a file like bellow:
id,code,name
1,PRT,Print
2,RFSH,Refresh
3,DEL,Delete
I need to convert the file like bellow:
[
{"id":1,"code":"PRT","name":"Print"},
{"id":2,"code":"RFSH","name":"Refresh"},
{"id":3,"code":"DEL","name":"Delete"}
]
CodePudding user response:
I would check https://github.com/FlatFilers/csvjson-csv2json
npm i csvjson-csv2json
const csv2json = require('./csv2json.js');
const csv = `album, year, US_peak_chart_post
The White Stripes, 1999, -
De Stijl, 2000, -
White Blood Cells, 2001, 61
Elephant, 2003, 6
Get Behind Me Satan, 2005, 3
Icky Thump, 2007, 2
Under Great White Northern Lights, 2010, 11
Live in Mississippi, 2011, -
Live at the Gold Dollar, 2012, -
Nine Miles from the White City, 2013, -`;
const json = csv2json(csv, {parseNumbers: true});
console.log(json);
If ts is not necessary case at least it is good example how was done in the js
CodePudding user response:
You can do something along the lines of (this is a very basic example mind you and it takes a lot of assumptions about your data...)
const rows = ['id,code,name',
'1,PRT,Print',
'2,RFSH,Refresh',
'3,DEL,Delete']
const header = rows.splice(0,1)[0].split(',');
const result = [];
rows.forEach((row) => {
const rowObj = {};
const values = row.split(',');
values.forEach((value, i) => rowObj[header[i]] = value);
result.push(rowObj);
})
console.log(result);