0

I am having difficulty how to convert csv file data into json objects.But I am getting uncaught TypeError: e.split is not a function Here is my code. HTML Code:

 <input type="file" accept=".csv" onchange="onFileChange()" />

JavaScript Code:

function onFileChange(event) {
  let file = event.target.files[0];
  const reader = new FileReader();
  reader.onload = e => e.target.result;
  reader.onload = e => {
    console.log(e.target.result);
    var lines = e.target.result.split("\n");
    var result = [];

    // NOTE: If your columns contain commas in their values, you'll need
    // to deal with those before doing the next step 
    // (you might convert them to &&& or something, then covert them back later)
    // jsfiddle showing the issue https://jsfiddle.net/
    var headers = lines[0].split(",");

    for (var i = 1; i < lines.length; i++) {
      var obj = {};
      var currentline = lines[i].split(",");
      for (var j = 0; j < headers.length; j++) {
        obj[headers[j]] = currentline[j];
      }
      result.push(obj);
    }

    //return result; //JavaScript object
    return JSON.stringify(result); //JSON
  };
  reader.readAsText(file);
}

Note: I have tried every possible code on stackoverflow, but I did not get what I want. I hope you can help me. Thanks

MikeM
  • 13,156
  • 2
  • 34
  • 47
user3718511
  • 317
  • 1
  • 3
  • 15
  • It looks like you're trying to call a method `split` on a [`change` event](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event), but the event does not have such a method. – jsejcksn Jul 18 '21 at 15:03
  • 1
    Does this answer your question? [Example JavaScript code to parse CSV data](https://stackoverflow.com/q/1293147/438273) – jsejcksn Jul 18 '21 at 15:04
  • I have edited my code. The error is gone. But still I am having issue to convert it into json objects. – user3718511 Jul 18 '21 at 15:06

0 Answers0