admin管理员组

文章数量:1332628

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 and this one with 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 ments 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>');

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./package/csvtojson and this one with stream parser https://github./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 ments 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>');
Share Improve this question edited Apr 13, 2016 at 1:39 Sai asked Apr 12, 2016 at 20:15 SaiSai 2,0426 gold badges34 silver badges56 bronze badges 1
  • 1 The format you are showing is not csv. In csv ma's separate fields/properties and lines represent records/objects. – Pero P. Commented Apr 12, 2016 at 20:27
Add a ment  | 

5 Answers 5

Reset to default 1

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

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

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.

本文标签: javascriptNodeJSConvert CSV to JSON Object arrayStack Overflow