【问题标题】:How to handle an "undefined" error while converting CSV file to JSON using Papa Parse framework?使用 Papa Parse 框架将 CSV 文件转换为 JSON 时如何处理“未定义”错误?
【发布时间】:2018-04-05 16:02:19
【问题描述】:

所以,这是我的 JS 代码:

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

这是我的测试 html 页面:

<!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>

当我尝试读取 myJSON 的长度时,我在 Chrome 控制台中收到错误消息:Uncaught TypeError: Cannot read property 'length' of undefined。为什么它是未定义的?它存在于控制台中!为什么会发生这种情况以及如何解决?如何将结果 myJSON 用作完全正常的静态 JSON?

【问题讨论】:

    标签: javascript json frameworks google-chrome-devtools papaparse


    【解决方案1】:

    您在 complete 回调函数中设置了 parsedJSON 的值。这可能会被称为AFTER,您的函数 parseCSV 返回了未定义的 parsedJSON 值。你需要用回调或承诺重写它。

    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);
    
        }
      });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 2021-11-13
      • 2021-06-23
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      相关资源
      最近更新 更多