Prakash
Prakash

Reputation: 336

How to convert .csv file to json?

I need to read a .csv file and convert the csv file to json format and pass the json to frontend

which is the best way to read a csv file and convert to json

Here my code is:

fs.readFile(req.files.file.path, function(ferr, file) {
        if (ferr) {
            res.json(HttpStatus.NOT_FOUND, { error: ferr });
        }
        if (file) { //here i will get my file
            //here i need to write code for convert the csv file to json
}

Upvotes: 2

Views: 152

Answers (1)

Shameem Ahmed Mulla
Shameem Ahmed Mulla

Reputation: 656

Here's the code to read .csv file and print it in json format.

Firstly install CSV module To do so un the following command from the console:

npm install csv

Then create a file and use the following code

var csv = require('csv');
// loads the csv module referenced above.

var obj = csv();

// gets the csv module to access the required functionality
function MyCSV(name, number, id) {
    this.FieldOne = name;
    this.FieldTwo = number;
    this.FieldThree = id;
};
​
var MyData = [];

obj.from.path('../THEPATHINYOURPROJECT/TOTHE/csv_FILE_YOU_WANT_TO_LOAD.csv').to.array(function (data) {
    for (var index = 0; index < data.length; index++) {
        MyData.push(new MyCSV(data[index][0], data[index][1], data[index][2]));
    }
    console.log(MyData);
});

var http = require('http');
//Load the http module.
​
var server = http.createServer(function (req, resp) {
    resp.writeHead(200, { 'content-type': 'application/json' });
    resp.end(JSON.stringify(MyData));
});

server.listen(8080);

Once completed start your app using

Node app

Upvotes: 1

Related Questions