0
const fs = require('fs');
 const csv =require('fast-csv');
 const path= require('path');
fs.createReadStream('translation.csv')
    .pipe(csv())
    .on('data',function (data) {
        console.log(data);
    })
    .on('end',function (data) {
        console.log('data end');

    })

This code read the csv file but I don't know who to convert into json file.Anyone please help me.

Adnan Butt
  • 11
  • 5
  • You have to provide more info. CSV is columnar data while JSON is key:value pair. Show us an example of your CSV and what you expect the json to look like – martin8768 May 02 '18 at 20:51
  • the csv file having four columns with header and values, the json file { "select dataa from": "Select data", "delivery ": "Delivery ", "starting time": "System Starting time!!", "end time": "System sending time } – Adnan Butt May 02 '18 at 20:57
  • 2
    Possible duplicate of [How to convert CSV to JSON in Node.js](https://stackoverflow.com/questions/16831250/how-to-convert-csv-to-json-in-node-js) – Adriano Resende May 02 '18 at 23:51

1 Answers1

0

I don't know how fast-csv works but I assume that the first emitted data is headers, you'll want to reference those, probably something like

const items = [];
// ...
.on(data, data => items.push(data));
// ...
const headers = items.shift();

then you can use a simple algorithm like this

// assuming data looks like so
const headers = ['a', 'b'];
const items = [[1, 2], [3, 4]];

const r = [];

for (let i = 0; i < items.length; i++) {
  let obj = {};
  let row = items[i];
    for (let j = 0; j < row.length;j++) {
    obj[headers[j]] = row[j];
   }
   r.push(obj);
}

console.log(r);
console.log(JSON.stringify(r));
martin8768
  • 565
  • 5
  • 20