TypeScript:在 JSON 中序列化 BigInt

Tri*_*sne 15 json global bigint typescript

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

我知道它是非标准的,我知道有一个纯 JavaScript 的包;但它不符合我的需求。我什至知道通过设置 来修复原始 JavaScript BigInt.prototype.toJSON。我需要的是某种方法来JSON.stringify在我的 TypeScript 代码中全局覆盖正常函数。

大约一年前,我发现了以下代码:

declare global
{
    interface BigIntConstructor
    {
        toJSON:()=>BigInt;
    }
}

BigInt.toJSON = function() { return this.toString(); };
Run Code Online (Sandbox Code Playgroud)

在某些网页上我无法再次找到。它曾经在我的另一个项目中工作过,但现在似乎不再工作了。我不知道为什么。

无论我对上面的行做什么,如果我尝试打印包含 BigInt 的 JSON,我会得到:TypeError: Do not know how to serialize a BigInt

如有任何帮助,我们将不胜感激 - 非常感谢。

Ale*_*hin 20

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

const obj = {
  foo: 'abc',
  bar: 781,
  qux: 9n
}

JSON.stringify(obj, (_, v) => typeof v === 'bigint' ? v.toString() : v)
Run Code Online (Sandbox Code Playgroud)


小智 10

这就是您要找的:

BigInt.prototype.toJSON = function() { return this.toString() }
Run Code Online (Sandbox Code Playgroud)

https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833

  • 如果您继续阅读,该链接中有一个 TypeScript 解决方案:https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-1006088574 (7认同)
  • 这适用于纯 JavaScript,但不适用于 TypeScript。使用 tsc 编译会出现错误 TS2339:类型“BigInt”上不存在属性“toJSON”。 (6认同)