convert CSV lines into Javascript objects convert CSV lines into Javascript objects node.js node.js

convert CSV lines into Javascript objects


By doing this:

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

you will have an array containing all rows as string

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

You have to break it again by comma using .split(','), then separate the headers and push it into an 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 an object like this:

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

See this FIDDLE


Using ES6/ES7 and some functional programming guidelines:

  • All variables are const (immutability)
  • Use map/reduce instead of while/for
  • All functions are Arrow
  • No dependencies
// Split data into lines and separate headers from actual data// using Array spread operatorconst [headerLine, ...lines] = data.split('\n');// Split headers line into an array// `valueSeparator` may come from some kind of argument// You may want to transform header strings into something more// usable, like `camelCase` or `lowercase-space-to-dash`const valueSeparator = '\t';const headers = headerLine.split(valueSeparator);// Create objects from parsing lines// There will be as much objects as linesconst objects = lines  .map( (line, index) =>    line      // Split line with value separators      .split(valueSeparator)      // Reduce values array into an object like: { [header]: value }      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce      .reduce(        // Reducer callback         (object, value, index) => ({          ...object,          [ headers[index] ]: value,        }),        // Initial value (empty JS object)        {}      )  );console.log("Objects:", objects);

For CSV files using , as separator and quotes string values, you can use this version:

// Split data into lines and separate headers from actual data// using Array spread operatorconst [headerLine, ...lines] = data.split('\n');// Use common line separator, which parses each line as the contents of a JSON arrayconst parseLine = (line) => JSON.parse(`[${line}]`);// Split headers line into an arrayconst headers = parseLine(headerLine);// Create objects from parsing lines// There will be as much objects as linesconst objects = lines  .map( (line, index) =>    // Split line with JSON    parseLine(line)      // Reduce values array into an object like: { [header]: value }       .reduce(         (object, value, index) => ({          ...object,          [ headers[index] ]: value,        }),        {}      )   );return objects;

Note: For big files, it would be better to work with streams, generators, iterators, etc.


You could try using MVC Razor,

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

The Json.Encode will serialize the initialized object to JSON format. Then the Html.Raw will prevent it from encoding the quotes to ".

Here the entire example