2

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!

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Harpreet, how would regex performance compare to string operations? I have begun creating functions using string operations to create these objects. As the data input may be vast and properties can tally much higher than 3, which approach would be ideal?
RegEx are faster as compared to normal string operations. Some String manipulation func also use RegEx internally. When your data is vast and complex RegEx is better but you have to Create an intelligent RegEx. I personally used string manipultation before RegEx and now I am totally shifted to RegEx. But still it depends on diffrent cases. Checkout these links - 1. blogs.msdn.com/b/oanapl/archive/2009/04/04/… 2.stackoverflow.com/questions/1062572/…
Fantastic! then this is EXACTLY what I was looking for, although it would be ideal to not have to specify the actual amount of columns, but instead have them as static
Thanks for accepting. Check this link, it is similar to your problem. stackoverflow.com/questions/24469220/…
oops, I meant dynamic not static, apologies
1

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"}
}

9 Comments

This is somewhat what I have been looking for, but what I really require is the array to contain Javascript objects instead of JSON strings. I was hoping the conversion from your code would be a simple manipulation of how each string(per object) is created. I hope this makes sense, I do like that you used an array of Keys from 1st line
@AbdulG - I'm not sure what you mean. The end result is an array of JS objects. Are you wanting to see only the algorithm for a single object, instead of the whole array?
Updated it to output the JS object. Also, fixed logic error.
Well, in all fairness, I did not specify it to be an array of JS objects over an array of JSON strings. What is being created here is definitely JSON strings. The only difference between the 2 of course are the "" around each property. Also, no need to see the algorithm. This is definitely on the right track
Hey AbdulG - Just because the property keys have quotes doesn't mean its a JSON string, its just means the JS Object's keys are strings. You can still reference the properties as json.Name, etc. Notice that we have to JSON.stringify the objects to turn them into strings.
|

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.