NodeJS BigInteger数字不传递给JSON对象

piok6c0g  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(142)

我有一个正在与之交互的智能合约,但我似乎无法使用这些变量形成一个合适的JSON对象。我已经能够拉取数据并记录它,我甚至能够拉取其他数据在其他函数没有问题,但这些数字返回一个错误时,试图使用这些值。
正如预期的那样,这段代码可以工作:

app.get('/stats', async (req, res) => {
try {
  res.json({'maxSupply':1});
} catch (error) {
  // Handle any errors that occur during the stats
  res.status(500).send("500 Error:");
}

这段代码可以工作:

app.get('/stats', async (req, res) => {
try {
  const totalSupply = await contract.methods.totalSupply().call();
  console.log("Total Supply: ",totalSupply)
  const remainingSupply = await contract.methods.remainingSupply().call();
  console.log("Remaining Supply: ",remainingSupply)

  // Create the high-level response object
  const responseObj = {
    totalSupply: Number(totalSupply),
    remainingSupply: Number(remainingSupply)
  };
  // Forward the response data to the client
  console.log("JSON", responseObj);

并且得到的输出是:

Server running on port 8080
Total Supply:  189880000000000000n
Remaining Supply:  810120000000000000n
JSON {
  totalSupply: 189880000000000000,
  remainingSupply: 810120000000000000
}

当我像这样添加json响应行时,我得到一个500错误。

// Forward the response data to the client
res.json({'totalSupply':totalSupply});

和/或

res.json(responseObj)

都失败了我错过了什么

ipakzgxi

ipakzgxi1#

使用JSON序列化像这样的大数字会遇到问题,特别是超过IEEE754浮点安全十进制数的数字[1]。
在这个例子中,在JavaScript中:

> 189880000000000000 > Number.MAX_SAFE_INTEGER
true

数字末尾的n表示它是一个原生BigInt值。[2]。这些是任意大小的仅限整数的数字。
你不能用JSON原生序列化BigInt。

JSON.stringify({ a: 1n })
Uncaught TypeError: Do not know how to serialize a BigInt

JSON只能使用IEEE标准来序列化数字。
您可以将数字序列化为字符串(String(18988n)),然后使用BigInt(s)将其从字符串强制转换为BigInt。
另一个选项是使用与JSON不同的编码,例如CBOR [3]。
除了无法序列化之外,对于IEEE浮点数,您也不能保证这些数量将正确执行算术,即对于分数(但当使用大于MAX_SAFE_INTEGER的数字时,也有整数的情况)

> 0.1 + 0.2
0.30000000000000004

所以如果你的数字确实是整数的话,你可能更喜欢BigInt。

相关问题