JS中的JSON.Parse返回未定义的-(Node.js应用程序)

fzsnzjdm  于 2023-01-30  发布在  Node.js
关注(0)|答案(1)|浏览(162)

我创建了一个将JSON转换为CSV的函数。但是JSON.parse返回未定义的值。请有人帮忙。

function JSONtoCSVConverter(JSONDataPath, showLabels) {
  var JSONData = fs.readFile(JSONDataPath, "utf-8", (err, fileContent) => {
    if (err) {
      console.log(err);
    } else {
      console.log(fileContent);
      JSON.parse(fileContent.toString().trim());
    }
  });

  console.log(JSONData);

  if (showLabels) {
    console.log(JSONData.slice(1, JSONData.length));
    var rowsOfDataArray = Object.keys(JSONData[0]);
    var rowsOfData = rowsOfDataArray.join(",") + "\n";
  }

  JSONData.forEach((object) => {
    var cellsOfDataArray = Object.values(object);
    cellsOfData = cellsOfDataArray.join(",") + "\n";
  });

  var csv = rowsOfData + "\n" + cellsOfData;
  return csv;
}

但是,我收到的错误是:
undefined TypeError: Cannot read properties of undefined (reading 'slice') at JSONtoCSVConverter (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\routes\reports.js:45:26) at C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\routes\reports.js:26:7 at Layer.handle [as handle_request] (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\layer.js:95:5) at C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\express\lib\router\index.js:280:10) at urlencodedParser (C:\Users\harsh\OneDrive\Documents\Visual Studio 2022\Web Development\contactStoreApp\node_modules\body-parser\lib\types\urlencoded.js:91:7)

uelo1irk

uelo1irk1#

JSON.parse返回未定义或fs.readFile返回undefinedfs.readFile不应返回任何内容
如果你想正确使用fs.readFile的结果,你必须把其余的代码放在回调函数中,如下所示:

function JSONtoCSVConverter(JSONDataPath, showLabels) {
    fs.readFile(JSONDataPath, "utf-8", (err, fileContent) => {
        if (err) {
            console.log(err);
        } else {
            console.log(fileContent);
            var JSONData = JSON.parse(fileContent.toString().trim());
            console.log(JSONData);

            if (showLabels) {
                console.log(JSONData.slice(1, JSONData.length));
                var rowsOfDataArray = Object.keys(JSONData[0]);
                var rowsOfData = rowsOfDataArray.join(",") + "\n";
            }

            JSONData.forEach((object) => {
                var cellsOfDataArray = Object.values(object);
                cellsOfData = cellsOfDataArray.join(",") + "\n";
            });

            var csv = rowsOfData + "\n" + cellsOfData;
            console.log(csv)
        }
    });
}

你可能已经注意到,这是相当混乱的-这种模式被称为callback hell,是JavaScript中使用非阻塞API时的一种老式编程。你也会注意到,我没有使用return来处理变量csv-要做到这一点,你必须向JSONtoCSVConverter传递一个回调函数作为第三个参数。
下面是这样做的一个例子(它被称为 * 回调模式 *)。

function JSONtoCSVConverter(JSONDataPath, cb) {
    fs.readFile(JSONDataPath, "utf-8", (err, fileContent) => {
        if (err) {
            cb(err, undefined);
        } else {
            var JSONData = JSON.parse(fileContent.toString().trim());
            cb(null, JSONData);
        }
    });
}

// use the function like this:
JSONtoCSVConverter('./file.json', function(err, data) {
  if (err) {
    console.error(err);  
  } else {
    console.log('here is JSON data:')
    console.log(data);
  }
});

但是,有一个更好的解决方案。
一个更好的解决方案是使用promises。NodeJS的最新版本有基于promises的API(例如,参见fs.promises.readFile,允许您这样使用它们:

const fs = require('fs')

async function JSONtoCSVConverter(JSONDataPath, showLabels) {
    var fileContent = await fs.promises.readFile(JSONDataPath, "utf-8")
    console.log(fileContent);
    var JSONData = JSON.parse(fileContent.toString().trim());
    console.log(JSONData);

    if (showLabels) {
        console.log(JSONData.slice(1, JSONData.length));
        var rowsOfDataArray = Object.keys(JSONData[0]);
        var rowsOfData = rowsOfDataArray.join(",") + "\n";
    }

    JSONData.forEach((object) => {
        var cellsOfDataArray = Object.values(object);
        cellsOfData = cellsOfDataArray.join(",") + "\n";
    });

    var csv = rowsOfData + "\n" + cellsOfData;
    return csv;
}

相关问题