通过Zoho Inventory API创建库存调整时item_id精度异常问题求助
解决Zoho Inventory API大整数item_id的精度问题
问题核心
Zoho返回的19位item_id超出JavaScriptNumber类型的15位精度上限,直接传递会被截断;用BigInt存储又会触发JSON序列化错误,导致API返回库存项错误。
方案1:直接传递字符串形式的数字(推荐优先尝试)
不少API文档标注要求数值类型,但后端实际能兼容字符串格式的数字(会自动转换)。你可以把item_id以字符串形式放到请求体里,彻底避免精度丢失:
const axios = require('axios'); async function createInventoryAdjustment() { const adjustmentData = { reason: "Stock count correction", adjustment_items: [ { item_id: "1234567890123456789", // 19位ID用字符串包裹 quantity_adjusted: 5, // 其他必填字段... } ] }; try { const response = await axios.post('https://www.zohoapis.com/inventory/v1/inventoryadjustments', adjustmentData, { headers: { 'Authorization': 'Zoho-oauthtoken YOUR_TOKEN', 'Content-Type': 'application/json' } }); console.log(response.data); } catch (err) { console.error(err.response.data); } }
方案2:自定义JSON序列化处理BigInt
如果API严格要求数值类型,你可以用BigInt存储ID,然后通过自定义序列化函数把BigInt转为字符串(避免序列化报错):
// 自定义BigInt序列化规则 function serializeBigInt(key, value) { if (typeof value === 'bigint') { return value.toString(); } return value; } async function createInventoryAdjustment() { const adjustmentData = { reason: "Stock count correction", adjustment_items: [ { item_id: BigInt("1234567890123456789"), // 用BigInt存储原始ID quantity_adjusted: 5, } ] }; try { const response = await axios.post('https://www.zohoapis.com/inventory/v1/inventoryadjustments', adjustmentData, { headers: { 'Authorization': 'Zoho-oauthtoken YOUR_TOKEN', 'Content-Type': 'application/json' }, transformRequest: [(data) => JSON.stringify(data, serializeBigInt)] }); console.log(response.data); } catch (err) { console.error(err.response.data); } }
方案3:用第三方库处理大整数序列化
使用专门处理大整数的JSON库json-bigint,它会自动处理超出精度的数字,避免序列化和精度丢失问题:
- 安装依赖:
npm install json-bigint
- 代码实现:
const JSONbig = require('json-bigint')({ storeAsString: true }); const axios = require('axios'); async function createInventoryAdjustment() { const itemIdStr = "1234567890123456789"; const adjustmentData = { reason: "Stock count correction", adjustment_items: [ { item_id: itemIdStr, quantity_adjusted: 5, } ] }; try { const response = await axios.post('https://www.zohoapis.com/inventory/v1/inventoryadjustments', adjustmentData, { headers: { 'Authorization': 'Zoho-oauthtoken YOUR_TOKEN', 'Content-Type': 'application/json' }, transformRequest: [(data) => JSONbig.stringify(data)] }); console.log(response.data); } catch (err) { console.error(err.response.data); } }
验证建议
- 先测试方案1,代码改动最小,多数API都支持这种兼容方式;
- 若方案1无效,再尝试方案2或3;
- 可以在Postman中把
item_id换成字符串形式测试,确认Zoho API是否接受该格式。
内容的提问来源于stack exchange,提问作者Zubair Javed
相关产品推荐
相关产品推荐

