最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert a CSV file into a JSON script using Node.js? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked May 7, 2016 at 8:32 NeoNeo 3665 silver badges15 bronze badges 1
  • npmjs./search?q=csv%20to%20json – Shanoor Commented May 7, 2016 at 8:37
Add a ment  | 

4 Answers 4

Reset to default 3

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

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

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

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

发布评论

评论列表(0)

  1. 暂无评论