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

前端JS如何简洁避免请求返回的大整数被自动取整?

问题:前端JSON解析大整数自动取整的简洁解决办法

我后端Web路由返回字典对象,但前端JS调用response.json()时,所有超过JS安全整数范围的整数值会被自动取整。示例代码如下:

let currentUserId;
let path = "/account?raw=True";
fetch(path)
.then(response => response.json())
.then(data => {
  if (BigInt(data.id) != null) {
    // 这里data.id已经被取整,转BigInt也无法恢复精确值
  }
})

现在不想逐个对ID或大整数执行data.id = BigInt(data.id),有没有简洁方法确保数值不被取整?


解决方案

  • 后端转字符串返回
    直接在后端把超过Number.MAX_SAFE_INTEGER(9007199254740991)的整数值转为字符串。前端拿到后可直接使用,需要计算时再转成BigInt,从根源避免精度丢失。

  • 自定义JSON解析逻辑
    放弃默认的response.json(),手动读取响应文本后用JSON.parse的reviver函数自动转换大整数:

    let currentUserId;
    let path = "/account?raw=True";
    fetch(path)
    .then(response => response.text())
    .then(text => JSON.parse(text, (key, value) => {
      if (typeof value === 'number' && Number.isInteger(value) && value > Number.MAX_SAFE_INTEGER) {
        return BigInt(value);
      }
      return value;
    }))
    .then(data => {
      // data.id已为BigInt类型,保留精确值
    })
    

    这种方式无需逐个处理字段,全局自动识别并转换符合条件的大整数。

  • 用第三方库解析
    比如json-bigint,它会自动将JSON中的大整数解析为BigInt:

    import JSONbig from 'json-bigint';
    
    let currentUserId;
    let path = "/account?raw=True";
    fetch(path)
    .then(response => response.text())
    .then(text => JSONbig.parse(text))
    .then(data => {
      // data.id为BigInt类型
    })
    

    注意:引入第三方库会增加项目依赖,需根据实际情况选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:20:06