简体   繁体   English

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

[英]JSON.Parse in JS is returning undefined - (Node.js app)

I created a function to convert JSON in CSV. However JSON.parse is returning undefined.我创建了一个 function 以在 CSV 中转换 JSON。但是 JSON.parse 返回未定义。 Please can someone help.请有人帮忙。

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

However, the error I have received is:但是,我收到的错误是:

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)

JSON.parse returns undefined or fs.readFile returns undefined ? JSON.parse返回未定义或fs.readFile返回undefined fs.readFile is not supposed to return anything fs.readFile 不应该返回任何东西

If you want to properly use the result of fs.readFile , you must put the rest of the code in the callback like so:如果你想正确使用fs.readFile的结果,你必须将代码的 rest 放在回调中,如下所示:

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

You might have noticed, this is quite messy - this sort of pattern has been dubbed callback hell , and is an older-style of programming in JavaScript when using non-blocking APIs.您可能已经注意到,这非常混乱 - 这种模式被称为回调地狱,并且是 JavaScript 中使用非阻塞 API 时的一种较旧的编程风格。 You will also have noticed that I'm not return ing the variable csv - to do that, you must pass a callback function to JSONtoCSVConverter as a third parameter.您还会注意到我没有return变量csv - 为此,您必须将回调JSONtoCSVConverter作为第三个参数传递给 JSONtoCSVConverter。

Here is an example of doing that (it is called the callback pattern ).这是一个这样做的例子(它被称为回调模式)。

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

But, there is a much better solution.但是,有一个更好的解决方案。

A better solution involves using promises.更好的解决方案涉及使用承诺。 Recent version of NodeJS have Promise-based APIs (ex. see fs.promises.readFile that allow you to use them like so:最新版本的 NodeJS 具有基于 Promise 的 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM