Create object on the fly from CSV

What I'm trying to do is create a object literal on the fly with dynamic properties.

I have an array containing the content (CSV format) of a file.

Each element is one line (the content was split with /\r?\n/).

The first element (first line) of that array contains the parameters I want to have for my object literal, separated by commas.

All the other elements are values (still CSV format) of the parameters set in the first line.

The code I have at the moment is the following :

function jsonDataArray(array) {
    var jsonResult = [],
        parameters = [],
        values;
    for(var i=0; i < array.length; i++) {
        if(i === 0) {
            var parameters = array[i].split(',');
            var objJSON = {};
            for(var k=0; k < parameters.length; k++) {
                objJSON.eval(parameters[k]);
            }
            continue;
        }
        values = array[i].split(',')
        for(var j=0; j < objJSON.length; j++) {
            objJSON[j] = values;
        }
        jsonResult.push(objJSON);
    }
    return jsonResult;
}

Now when I launch this code in node, the objJSON.eval(parameters[k]) line seems to be the one where the problem is, but I wasn't able to solve the problem.

So basically my questions are the following :

  • How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in ?

  • Is it safe to parse new lines with this : /\r?\n/ ?

Thank you in advance for your help !

EDIT : I mistakenly used the term JSON to mean object literal so I corrected the question. I didn't modify the function though so that I don't add errors in the code by mistake.

It looks to me you want an array of objects, each object having keys from the first row (headers).

The following code assumes you already broke the csv into each line via \r?\n

(function() {
  var csv = [];
      csv.push('name,age,gender');
      csv.push('jake,13,m');
      csv.push('sarah,15,f');
      csv.push('john,18,m');
      csv.push('nick,13,m');

  console.log(csv);

  function jsonDataArray(array) {
    var headers = array[0].split(',');
    var jsonData = [];
    for ( var i = 1, length = array.length; i < length; i++ )
    {
      var row = array[i].split(',');
      var data = {};
      for ( var x = 0; x < row.length; x++ )
      {
        data[headers[x]] = row[x];
      }
      jsonData.push(data);

    }

    return jsonData;
  }

  console.log(jsonDataArray(csv));


})();

http://jsbin.com/igiwor/2/edit

This will produce something like the follow:

[{ name="jake",  age="13",  gender="m"},
{ name="sarah",  age="15",  gender="f"}, 
{ name="john",  age="18",  gender="m"},
{ name="nick"  age="13",  gender="m"}]

Here is my CSV-parse function, I hope it helps:

function parseCSV(input) {
    var rows = input.split(/\r?\n/);
    var keys = rows.shift().split(",");
    return rows.map(function(row) {
        return row.split(",").reduce(function(map, val, i) {
            map[keys[i]] = val;
            return map;
        }, {});
    });
}

How should I proceed to have the parameters from the first line set as parameters of a JSON object + fill the values of the other lines in?

Just loop through the values. Then, the key as which the values[i] is added to the object is parameters[i]. In my version that is the line map[keys[i]] = val;

Is it safe to parse new lines with this: /\r?\n/?

I think yes.

I think you can just say the following, but I'm not sure what <somevalue> should be.

      objJSON[parameters[k]] = <somevalue>;

In any case, consider the following,

var anObj = {};

anObj["a1"] = "sam";
anObj["a2"] = 5;

This is the same as

var anObj = { a1 : "sam", a2 : 5 };