TypeScript:在 JSON 中序列化 BigInt

TypeScript: serialize BigInt in JSON

我正在寻找一种方法来强制 JSON.stringify 始终打印 BigInts 而不会抱怨。

我知道它是非标准的,我知道有一个 pure 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.

感谢任何帮助 - 非常感谢。

您可以像这样为 JSON.stringify 使用 replacer 参数:

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。