fix:大整数精度问题使用正则替换,在JSON.parse前把大数字引起来
This commit is contained in:
parent
c00e538814
commit
0be4cb1450
51
utils/api.js
51
utils/api.js
@ -362,48 +362,15 @@ export { buildFormBodyWithImages }
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 安全解析 JSON,将超出 JS 安全整数范围的数字转为字符串
|
* 安全解析 JSON,将超出 JS 安全整数范围的数字转为字符串
|
||||||
* uni.request 可能会自动解析 JSON,所以返回的数据可能是对象或字符串
|
* 必须用正则提前处理原始文本,因为 JS 的 JSON.parse 在数字解析阶段
|
||||||
|
* 就已经丢失精度了,reviver 回调拿到的也是错误值
|
||||||
*/
|
*/
|
||||||
function safeJsonParse(data) {
|
function safeJsonParse(text) {
|
||||||
if (typeof data === 'string') {
|
if (typeof text !== 'string') return text
|
||||||
return JSON.parse(data, function(key, value) {
|
// 把所有 16 位及以上数字(JSON value 位置)用引号包起来
|
||||||
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
// 这样 JSON.parse 会当字符串处理,不会丢精度
|
||||||
return String(value)
|
text = text.replace(/:\s*(-?\d{16,})\s*([,}\]])/g, ':"$1"$2')
|
||||||
}
|
return JSON.parse(text)
|
||||||
return value
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// data 已经是对象(uni-app 自动解析了),修复所有大整数字段
|
|
||||||
if (data && typeof data === 'object') {
|
|
||||||
fixLargeInts(data)
|
|
||||||
}
|
|
||||||
return data
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 递归修复对象中的大整数(超过 JS 安全范围的 number → string)
|
|
||||||
*/
|
|
||||||
function fixLargeInts(obj) {
|
|
||||||
if (obj === null || obj === undefined) return
|
|
||||||
if (typeof obj !== 'object') return
|
|
||||||
|
|
||||||
if (Array.isArray(obj)) {
|
|
||||||
for (var i = 0; i < obj.length; i++) {
|
|
||||||
if (obj[i] !== null && obj[i] !== undefined && typeof obj[i] === 'object') {
|
|
||||||
fixLargeInts(obj[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
for (var key in obj) {
|
|
||||||
var val = obj[key]
|
|
||||||
if (typeof val === 'number' && !Number.isSafeInteger(val)) {
|
|
||||||
obj[key] = String(val)
|
|
||||||
} else if (val !== null && typeof val === 'object') {
|
|
||||||
fixLargeInts(val)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -418,6 +385,7 @@ export function getShopList(params = {}) {
|
|||||||
uni.request({
|
uni.request({
|
||||||
url: url,
|
url: url,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
|
dataType: 'text',
|
||||||
header: {
|
header: {
|
||||||
'Authorization': 'Bearer ' + token
|
'Authorization': 'Bearer ' + token
|
||||||
},
|
},
|
||||||
@ -451,6 +419,7 @@ export function getShopDetail(params = {}) {
|
|||||||
uni.request({
|
uni.request({
|
||||||
url: url,
|
url: url,
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
|
dataType: 'text',
|
||||||
header: {
|
header: {
|
||||||
'Authorization': 'Bearer ' + token
|
'Authorization': 'Bearer ' + token
|
||||||
},
|
},
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user