AbdulG
AbdulG

Reputation: 755

Converting result of FileReader to javascript objects

I am using the Javascript FileReader. I would like to read in the result of the FileReader and then convert each record into a JS object. Using the following code:

$("#csv").bind("change", function (event) {
            var reader = new FileReader();
            reader.onload = function (theFile) {
                try {
                    var input = $.csv.toArrays(theFile.target.result);
                    alert("CSV loaded successfully");
                    alert(input);
                }
                catch (e) {
                    alert("CSV Parse error.");
                    return;
                }
            };
            reader.readAsText(event.target.files[0]);
        });
    }

alert(input) will display the entire csv file as a string. How would I go about creating an array of javascript objects or JSON strings from this input? In other words, I would assume I would need to read in the 1st line as the set of properties, then each record thereafter would then create an object with the set of properties and insert each of these objects into an array.

For example, from the following string:

Name,Age,Gender

John,20,Male

I would like to create an object as:

{ Name: "John", Age: 20, Gender: "Male" }

Thanks in advance!

Upvotes: 2

Views: 1755

Answers (2)

mtyson
mtyson

Reputation: 8550

Basically, break the data into lines, iterate over each line, saving the first line as the keys. Then create an object for each data line, with the key line providing the property names, and the data line providing the values. Save each object to an array.

Here's a sample: http://jsfiddle.net/phRqb/1/

Below I have commented inline:

var data = "Name,Age,Gender\n" +
"John,20,Male\n"+
"Cristine,34,FeMale\n";
var lines = data.trim().split("\n"), // break data into lines
    keys = [],
    jsonArr = [],
    json = {};
for (lineCount = 0; lineCount < lines.length; lineCount++){ // iterate over lines
  var lineData = lines[lineCount].split(',');
  if (lineCount === 0){
    keys = lineData; // save the keys from the first line into array
  } else {
    json = {};
    for (dataCount = 0; dataCount < lineData.length; dataCount++){
      json[keys[dataCount]] = lineData[dataCount]; // for each data line, create a json
      // object that points from the key to the data element
    }
    jsonArr.push(json); // save the objects to an array
  }
}
for (x in jsonArr){
  $('body').append("<div>"+JSON.stringify(jsonArr[x])+"</div>");     
  // outputs: 
  //   {"Name":"John","Age":"20","Gender":"Male"}
  //   {"Name":"Cristine","Age":"34","Gender":"FeMale"}
}

Upvotes: 1

Harpreet Singh
Harpreet Singh

Reputation: 2671

With RegEx

/[\w .]+(?=,?)/g

you can extract data from the csv file in the format as you mentioned(if format of .csv file and data is different then RegEx need to be changed).

Demo-RegEX

Working-Demo

Sample Data acc. to given format

Name,Age,Gender
John,20,Male
Cristine   ,34,FeMale
Kate Wilson,65,   FeMale
Mike,45,Male
Peter,23,Male
Katty,11,FeMale
Sandy,78,Mal

Code

var str = $('#regex_string').val();
var extractValidString = str.match(/[\w .]+(?=,?)/g)

var noOfCols = 3
//in your case it is name,age,gender so we need 3

var objFields = extractValidString.splice(0,noOfCols);
//extract columns - First Row
var arr = [];
while(extractValidString.length>0) {
    var obj = {};
    //extract remaining rows one by one
    var row = extractValidString.splice(0,noOfCols)
    for(var i=0;i<row.length;i++) {
        //make an object and put each column and set its data
        obj[objFields[i]] = row[i].trim()
    }
    //push row to an array
    arr.push(obj)
}
console.log(arr);

//output
[Object, Object, Object, Object, Object, Object, Object]
    0: Object
        Age: "20"
        Gender: "Male"
        Name: "John"
    1: Object
        Age: "34"
        Gender: "FeMale"
        Name: "Cristine"
    2: Object
        Age: "65"
        Gender: "FeMale"
        Name: "Kate Wilson"
    3: Object
        Age: "45"
        Gender: "Male"
        Name: "Mike"
    4: Object
        Age: "23"
        Gender: "Male"
        Name: "Peter"
    5: Object
        Age: "11"
        Gender: "FeMale"
        Name: "Katty"
    6: Object
        Age: "78"
        Gender: "Male"
        Name: "Sandy"
        length: 7

Upvotes: 1

Related Questions