我正在寻找一种方法来强制
JSON.stringify
始终打印 BigInt
s 而不会抱怨。
我知道它是非标准的,我知道在纯 JavaScript 中有一个包;但它不符合我的需要。我什至知道通过设置
BigInt.prototype.toJSON
来修复原始 JavaScript。我需要的是在我的 TypeScript 代码中全局覆盖正常的JSON.stringify
函数。
大约一年前我发现了以下代码:
declare global
{
interface BigIntConstructor
{
toJSON:()=>BigInt;
}
}
BigInt.toJSON = function() { return this.toString(); };
在某些网页上我无法再次找到。它曾经在我的另一个项目中工作,但它似乎不再工作了。我不知道为什么。
无论我对上面的行做什么,如果我尝试打印包含 BigInt 的 JSON,我都会得到:
TypeError: Do not know how to serialize a BigInt
.
感谢任何帮助 - 非常感谢。
您可以像这样使用
replacer
参数来代表 JSON.stringify
:
const obj = {
foo: 'abc',
bar: 781,
qux: 9n
}
JSON.stringify(obj, (_, v) => typeof v === 'bigint' ? v.toString() : v)
这就是您要找的:
BigInt.prototype.toJSON = function() { return this.toString() }
https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833
我需要让 JSON.stringify 在其中一个依赖项中工作,所以我不能使用上面的答案。相反,我创建了一个 patch.js 文件:
BigInt.prototype.toJSON = function() {
return this.toString()
}
然后在我的 TypeScript 源代码的开头添加:
require('patch.js')
之后,JSON.stringify 可以毫无问题地处理 BigInts。