You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中替换JSON的minPrice为BigNumber格式?

问题:调整JSON结构使其匹配目标格式

目标JSON结构

{"tokenId":1,"uri":"ipfs://bafy...","minPrice":{"type":"BigNumber","hex":"0x1a"},"signature":"0x51xxx"}

当前输出的JSON

{
    "tokenId": "1",
    "uri": "ipfs://baf...",
    "minPrice": 0.26,
    "signature": "0x..."
}

现有获取数据的代码

async function redeem(cid) {
  fetch(`http://localhost:4000/getDetails/${cid}`).then(response => {
    return response.json()
  }).then((async output=> {
    console.log(output[0]); // 打印当前JSON
    const obj = output[0].minPrice.toString();
    const price = ethers.utils.parseUnits(obj,2);
    console.log(price) 
  }))
}

解决方案

直接修改现有代码,把原对象里的tokenId转成数字,同时替换minPrice为目标要求的BigNumber结构即可:

async function redeem(cid) {
  fetch(`http://localhost:4000/getDetails/${cid}`).then(response => {
    return response.json()
  }).then(async output=> {
    // 取出第一个数据对象
    const targetItem = output[0];
    // 1. 把tokenId从字符串转成数字
    targetItem.tokenId = Number(targetItem.tokenId);
    // 2. 转换minPrice为BigNumber结构
    const priceStr = targetItem.minPrice.toString();
    const price = ethers.utils.parseUnits(priceStr, 2);
    targetItem.minPrice = {
      type: "BigNumber",
      hex: price._hex // ethers的BigNumber自带_hex属性,直接用就行
    };
    // 现在targetItem就是完全匹配目标结构的对象了
    console.log(targetItem);
  })
}

关键说明

  • tokenId需要从字符串"1"转为数字1,直接用Number()转换即可
  • ethers生成的BigNumber对象自带_hex属性,直接提取这个值就能得到目标里的十六进制字符串
  • 替换原对象的对应字段后,最终的targetItem就和期望的JSON结构完全一致了

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:15:40