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
| 归档时间: |
|
| 查看次数: |
22434 次 |
| 最近记录: |