Search code examples
javascriptjsonframeworksgoogle-chrome-devtoolspapaparse

How to handle an "undefined" error while converting CSV file to JSON using Papa Parse framework?


So, this is my JS code:

function main(){
    let myJSON = parseCSV();
    console.log(myJSON);
    let myCSV = transformCSV(myJSON);
    console.log(myCSV);
}

function parseCSV(){
    let parsedJSON;
    let selectedFile = document.getElementById('fileIn').files[0];
    Papa.parse(selectedFile, {
        complete: function(results) {
            parsedJSON = results.data;
            console.log(results.data);
            console.log(typeof(results.data));
        }
    });
    return parsedJSON;
}

function transformCSV(JSONIn){
    let csvOut = ""; // i will do something here later
    let dCol = ""; // i will do something here later
    let dRow = ""; // i will do something here later
    for (let i = 0; i < JSONIn.length - 1; i++) {
        // i will do something here later
    }
    return csvOut;
}

And this is my test html page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src=".\transformCSV.js"></script>
    <script src=".\node_modules\papaparse\papaparse.js"></script>
    <input type="file" id="fileIn">
    <input type="button" value="click!" onclick="main()">
</body>
</html>

When I try to read length of myJSON, I get error message in Chrome console: Uncaught TypeError: Cannot read property 'length' of undefined. Why is it undefined? It is present in console! Why does this happen and how to fix it? How to work with resulted myJSON as a perfectly normal static JSON?


Solution

  • You set the value of parsedJSON in the complete callback function. This will probably be called AFTER your function parseCSV has returned the undefined value of parsedJSON. You need to rewrite it with a callback or promise.

    parseCSV(function (myJSON) {
      console.log(myJSON);
      let myCSV = transformCSV(myJSON);
      console.log(myCSV);
    });
    
    function parseCSV(callback){
      let parsedJSON;
      let selectedFile = document.getElementById('fileIn').files[0];
      Papa.parse(selectedFile, {
        complete: function(results) {
            parsedJSON = results.data;
            callback(parsedJSON);
    
        }
      });
    
    }