3

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>');
1
  • 1
    The format you are showing is not csv. In csv comma's separate fields/properties and lines represent records/objects. Commented Apr 12, 2016 at 20:27

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

6 Comments

using plain split and map works really good especially with the => ECMA syntax (not pretty sure what it is called is it Arrow functions?), so as i said this is pretty sleek and clean.. just wondering what if i have the CSV data as this 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5' and the resulting JSON should look something like this,
{ fruits: [ { "name": "apples", "value": "1" }, { "name": "oranges", "value": "2" }, { "name": "grapes", "value": "3" }.... ] }
awesome, that would work and it looks like we have limited support for Arrow functions as per caniuse.com/#search=%3D%3E, no worries about IE but it looks like there is no support on Safari, IOS safari and android... just trying to see if we can use the traditional map function to achieve this so i believe the support spectrum would be large.. thoughts?
@Sai yes, it depends on your needs. If you want to support older browser you should use plain functions instead of arrow or use transpilers like babel.js
Yep, i'm looking for support in mobile browsers as well, i like the babel.js idea and it looks like they have npm support.. so for now i just modified the split and map functions like below so it works in all browsers (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
|
1

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

Comments

1

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

2 Comments

the data ("apples,oranges,grapes,peach,pineapple") i projected is just an example, actually in the application i'll be getting approximately 1100 values with comma separated... do you think that split and map approach would work even in that case without impacting memory..
Actually, the resulting JSON will store all your data. So you will use this memory anyway. Also, 1100 values is a relatively small bundle of data.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.