Neo
Neo

Reputation: 366

How to convert a CSV file into a JSON script using Node.js?

test.csv file has:

"Id","UserName","Age"
"01","Sam Smith","33"
"02","Fred Frankly","44"
"03","Zachary Zupers","55"

acpected output: as Json File

[{"id":01,"User Name": " Sam Smith", "Age":"33"},
{"id":03,"User Name": " Fred Frankly", "Age":"44"}
{"id":03,"User Name": "Aachary Zupers", "Age":"55"}
]

I tried to solve like this using node.js

var fs = require("fs");

var data = fs.readFileSync('test.csv');
var stringData=data.toString();

console.log(stringData);
var arrayOne= stringData.split('\r\n');

var header=arrayOne[0].split(',');
var noOfRow=arrayOne.length;
var noOfCol=header.length;

var jArray=[];

var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {

    for (j = 0; j< noOfCol; j++) {

        var myNewLine=arrayOne[i].split(',');
        jArray.push( '{'+header[j]+':'+myNewLine[j]+'}');               
    };
};

console.log( jArray);

this is the output I got when I run the above code: output Image In the above code I have just tried to show in json script. But If you can do that. Please provide the code to convert the displayed output into a .json file.

Please help me I shall be thankful to you.

Upvotes: 1

Views: 6020

Answers (4)

user4466350
user4466350

Reputation:

If you care to not re invent the wheel,

Given a csv such

NAME, AGE
Daffy Duck, 24
Bugs Bunny, 22

you could do like this

var csv = require('csv-parser')
var fs = require('fs')

fs.createReadStream('some-csv-file.csv')
  .pipe(csv())
  .on('data', function (data) {
    console.log('Name: %s Age: %s', data.NAME, data.AGE)
  })

see more here

Upvotes: 1

Paarth
Paarth

Reputation: 10377

As ShanShan mentioned you can leverage an external library for this in a real project, but I've made some modifications to your code that should do what you want in case you're doing this as a learning experience.

I've tried to keep the code roughly the same. There are two major changes. First, rather than construct a string with the content I'm creating an object that stores the data that you're interested in for each row. Because this object is on a per-row level, this is in the outer loop that handles rows. Second, I'm stripping out the first and last character of the header and value text (the quotes). Because you're interepreting the CSV as a string and splitting based on that, it still contains the quotes. In the real world you might want to extract this with a regex or a replace function, but I tried to keep it simple so it uses substring instead.

The code below:

var fs = require("fs");

var data = fs.readFileSync('test.csv');
var stringData=data.toString();

console.log(stringData);
var arrayOne= stringData.split('\r\n');

var header=arrayOne[0].split(',');
var noOfRow=arrayOne.length;
var noOfCol=header.length;

var jArray=[];

var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {

    var obj = {};
    var myNewLine=arrayOne[i].split(',');

    for (j = 0; j< noOfCol; j++) {
        var headerText = header[j].substring(1,header[j].length-1);
        var valueText = myNewLine[j].substring(1,myNewLine[j].length-1);
        obj[headerText] = valueText;
    };
    jArray.push(obj);
};

console.log( jArray);

Upvotes: 3

user5383152
user5383152

Reputation:

This should work

var fs = require('fs');

var data = fs.readFileSync('test.csv');
var parsed = data.toString().split('\r\n').splice(1).map(function(d) {
    var splitted = d.split(',');
    return {
        id: parseInt(JSON.parse(splitted[0])),
        user_name: JSON.parse(splitted[1]),
        age: parseInt(JSON.parse(splitted[2]))
    };
});

console.log(parsed);

Upvotes: 2

F&#225;bio Almeida
F&#225;bio Almeida

Reputation: 305

try this:

...    
var jArray=[];

var i=0,j=0;
for (i = 1; i < noOfRow-1; i++) {

    for (j = 0; j< noOfCol; j++) {

        var myNewLine=arrayOne[i].split(',');
        jArray.push(JSON.parse( '{'+header[j]+':'+myNewLine[j]+'}'));
    };
};



fs.writeFile('test.json', JSON.stringify(jArray), function (err) {
  if (err) return console.log(err);
  console.log('ok');
});

console.log( jArray);

Upvotes: 2

Related Questions