【问题标题】:JSON file getting passed as JavaScript object in Express Node.js?JSON 文件在 Express Node.js 中作为 JavaScript 对象传递?
【发布时间】:2022-01-13 08:58:00
【问题描述】:

我正在使用以下行在我的代码中导入 JSON 文件。但是,jsonConfig 变量获取的不是配置文件,而是一个 JavaScript 对象,我可以直接访问 jsonConfig.children。为什么会这样?我怎样才能只导入 JSON 文件而不是对象?

const jsonConfig = require('../../config/myconfig.json');

【问题讨论】:

  • 这就是应该发生的。如果您希望文件内容为文本(这就是我假设您所说的“导入 json 文件”的意思,但并不完全清楚您想要什么或为什么),请使用 fs 来阅读它。
  • 这里是 a reference to the documentation for require():“和 .json 文件被解析为 JSON 文本文件。”

标签: javascript node.js express


【解决方案1】:

这就是使用你的方法应该发生的事情,如果你想以文本形式访问文件的内容,你应该使用 fs

fs.readFile('../../config/myconfig.json', function read(err, data) {
    if (err) {
        throw err;
    }
    const content = data;

    // Invoke the next step here however you like
    console.log(content);   //Here you have the contents of your file

});

【讨论】:

    【解决方案2】:

    JSON 代表 Javascript Object Notation,因此 JSON 是 javascript 中的有效对象,因此您正在获取一个对象,您可以使用 object notation 访问这些值,如果想要获取一个字符串,您可以使用 JSON。 stringify 将您的对象转换为字符串。

    const jsonConfig = require('../../config/myconfig.json');
    const jsonString = JSON.stringify(jsonConfig);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 2012-06-12
      • 2012-02-01
      • 2013-05-28
      • 2016-04-28
      • 2019-01-24
      相关资源
      最近更新 更多