简体   繁体   中英

NodeJS - Convert CSV to JSON Object array

I'm trying to convert the below CSV formatted data into a JSON object array,

CSV formatted data: apples,oranges,grapes,peach,pineapple

JSON Object Array: {
                     fruits: [
                       {
                          "name": "apples"
                       },
                       {
                          "name": "oranges"
                       },
                       {
                          "name": "grapes"
                       },
                       {
                          "name": "peach"
                       },
                       {
                          "name": "pineapple"
                       }
                     ]
                   }

I referred this npm package https://www.npmjs.com/package/csvtojson and this one with stream parser https://github.com/nicolashery/example-stream-parser , but not sure how this may fit with my need.

Can anyone please suggest a way to convert this CSV data to a JSON object array in the format that's been posted.

Solution for the above query (Please refer the below comments section for more details),

var res = {};

res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5'
.split(',').map(function (fruit) { //as did by @Dmitriy Simushev in the below reply
    return {
      "name": fruit.split('|')[0],
      "value": fruit.split('|')[1]
    }
});

document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>');

You can easily combine String.prototype.split with Array.prototype.map to achieve the target.

Here is an example of how it could be done:

var data = "apples,oranges,grapes,peach,pineapple";

// Wrap fruits names with object,
var fruits = data.split(',').map(function(fruit) {
    return {name: fruit}
});

// Wrap fruits set with outer object.
var json = {fruits: fruits};

// Show the result.
console.dir(json);

 var csv_data = 'apples,oranges,grapes,peach,pineapple'; var csv_array = csv_data.split(','); var object = {}; var arr = []; for(var i=0; i<csv_array.length; i++){ arr.push({name:csv_array[i]}); } object['fruits'] = arr; console.log(object); 

You can use plain javascript, with split and map functions

 var res = {}; res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5' .split(',').map(e => ({ "name": e.split('|')[0], "value": e.split('|')[1] })); document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>'); 

As shown in the docs , you can convert your csv file like this

var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromFile("./yourCSVfile.csv", function(err, result){
   // do something with "result", it's json
});

Every answer so far is not reflecting that your data is stored in a file. And I think this is what you are looking for. You can use simple Node.js streams to achieve this:

var fs = require('fs');
var es = require('event-stream');

fs.createReadStream('data.csv')
.pipe(es.split())
.on('data', (row) => {
  console.log({
    fruits: row.toString().split(',').map((fruit) => {
      return {
        name: fruit.trim()
      }
    })
  });
});

You need to install event-stream npm install event-stream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM