【问题标题】:Please explain why JSON.stringify output differs from toString output in this short example请在这个简短的示例中解释为什么 JSON.stringify 输出与 toString 输出不同
【发布时间】:2023-04-02 00:57:01
【问题描述】:

这看起来类似于console.log inconsistent with JSON.stringify,但是:我想知道屏幕后面到底发生了什么,因为我无法理解这里到底发生了什么,以及为什么 JSON.stringify() 不显示错误文本.这是我的代码(保存在 firstio.js 中)

var fs = require('fs')

try {
  var file = fs.readFileSync(process.argv[2])
}
catch(error) {
  console.log(error.toString());
  console.log(JSON.stringify(error, null, 2));
  process.exit()
}
console.log(file.toString().split("\n").length - 1)

运行如下:node firstio.js输出如下:

TypeError: path must be a string
{}

如果 JSON.stringify 正在转换错误对象,那么 toString() 显然 可以 找到的错误文本在哪里?

如下运行时:node firstio.js nonexistingfile 输出为:

Error: ENOENT, no such file or directory 'nonexistingfile'
{
  "errno": -2,
  "code": "ENOENT",
  "path": "nonexistingfile",
  "syscall": "open"
}

【问题讨论】:

  • 因为它是两个完全不同的功能?
  • 字符串化进程枚举属性。也许错误没有任何。
  • 好的,在为 Javascript 搜索类似 PHP 的 var_dump() 时,SO 上的最佳答案提到了 JSON.stringify(),但是 - 正如我发现并想知道的那样 - 这不适用于误差变量。原来这就是答案:错误变量不是可枚举的对象。谢谢@Radek Pech。我会标记你的答案。 JS 是否有等价的 var_dump() 仍然存在问题。不,它没有,虽然 console.dir() 似乎很接近。
  • Radek,如果您创建答案,我会将其标记为已接受。

标签: javascript json


【解决方案1】:

方法JSON.stringify()根据对象的enumarable properties处理对象。

但是window.Error 对象没有任何可枚举的属性,因此JSON.stringify(error) 只返回空对象。

您可以直接将错误写入控制台:

console.log(new Error('Something happened'));

这将输出Error: Something happened

或者您可以编写自己的方法来字符串化错误;见Is it not possible to stringify an Error using JSON.stringify?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多