-1

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"}
]
R. Richards
  • 24,603
  • 10
  • 64
  • 64
  • 1
    Did you look on https://stackoverflow.com/questions/67348284/converting-csv-to-json-using-javascript ? – Alex Yu Sep 15 '21 at 07:39
  • 1
    Does this answer your question? [Converting CSV to JSON using JavaScript](https://stackoverflow.com/questions/67348284/converting-csv-to-json-using-javascript) – Alex Yu Sep 15 '21 at 07:39

2 Answers2

0

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

askeet
  • 689
  • 1
  • 11
  • 24
  • Though I'd like to use jscript code, but I could not resolve it when delimiter char is part of the content. csvjson-csv2json is working fine for me. thanks – Rafael Segura Sep 16 '21 at 12:18
0

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);