Convert CSV Strings to Javascript Objects

I have a simple csv file

people.csv:

fname, lname, uid, phone, address
John, Doe, 1, 444-555-6666, 34 dead rd
Jane, Doe, 2, 555-444-7777, 24 dead rd
Jimmy, James, 3, 111-222-3333, 60 alive way

What I want to do is get each CSV line, convert it to a JavaScript object, save it to an array, and then convert the array to a JSON object.

server.js:

var http = require('http');
var url  = require('url');
var fs = require('fs');

var args = process.argv;
var type = args[2] || 'text';
var arr = []; 
var bufferString; 

function csvHandler(req, res){
  fs.readFile('people.csv',function (err,data) {

  if (err) {
    return console.log(err);
  }

  //Convert and store csv information into a buffer. 
  bufferString = data.toString(); 

  //Store information for each individual person in an array index. Split it by every newline in the csv file. 
  arr = bufferString.split('\n'); 
  console.log(arr); 

  for (i = 0; i < arr.length; i++) { 
    JSON.stringify(arr[i]); 
  }

  JSON.parse(arr); 
  res.send(arr);  
});
}

//More code ommitted

My question is, am I really converting these CSV strings to Javascript objects when I call the .split ('\ n') method on bufferString or is there any other way to do this?

+4
source share
3 answers

By doing this:

arr = bufferString.split('\n'); 

you will have an array containing all the rows as a string

["fname, lname, uid, phone, address","John, Doe, 1, 444-555-6666, 34 dead rd",...]

You need to break it with a comma using .split(','), then separate the headers and paste it into a Javascript object:

var jsonObj = [];
var headers = arr[0].split(',');
for(var i = 1; i < arr.length; i++) {
  var data = arr[i].split(',');
  var obj = {};
  for(var j = 0; j < data.length; j++) {
     obj[headers[j].trim()] = data[j].trim();
  }
  jsonObj.push(obj);
}
JSON.stringify(jsonObj);

Then you will have the following object:

[{"fname":"John",
  "lname":"Doe",
  "uid":"1",
  "phone":"444-555-6666",
  "address":"34 dead rd"
 }, ... }]

FIDDLE

+6

MVC Razor,

<script type="text/javascript">
    MyNamespace.myConfig = @Html.Raw(Json.Encode(new MyConfigObject()));
</script>

Json.Encode JSON. Html.Raw .

0

You can use lodash (or underscore) to help with this.

var objects = _.map(arr, function(item){return item.split(',');});
var headers = objects[0];
objects.splice(0, 1); // remove the header line
populatedObject = [];
objects.forEach(function(item){
   var obj = _.zipObject(headers, item);
   populatedObject.push(obj);
});

The .zipObject method will map each heading to each value in the items array and create an object.

0
source

All Articles