fix:修复uni-app自动解析JSON导致大整数丢失的问题,改用递归修复
This commit is contained in:
parent
6bcfacd2d1
commit
c00e538814
44
utils/api.js
44
utils/api.js
@ -362,14 +362,48 @@ export { buildFormBodyWithImages }
|
||||
|
||||
/**
|
||||
* 安全解析 JSON,将超出 JS 安全整数范围的数字转为字符串
|
||||
* uni.request 可能会自动解析 JSON,所以返回的数据可能是对象或字符串
|
||||
*/
|
||||
function safeJsonParse(text) {
|
||||
return JSON.parse(text, function(key, value) {
|
||||
function safeJsonParse(data) {
|
||||
if (typeof data === 'string') {
|
||||
return JSON.parse(data, function(key, value) {
|
||||
if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
||||
return String(value)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -384,12 +418,11 @@ export function getShopList(params = {}) {
|
||||
uni.request({
|
||||
url: url,
|
||||
method: 'GET',
|
||||
dataType: 'text',
|
||||
header: {
|
||||
'Authorization': 'Bearer ' + token
|
||||
},
|
||||
success: (res) => {
|
||||
var data = typeof res.data === 'string' ? safeJsonParse(res.data) : res.data
|
||||
var data = safeJsonParse(res.data)
|
||||
console.log('【店铺列表】响应:', JSON.stringify(data))
|
||||
if (res.statusCode === 200 && data && data.code === 0) {
|
||||
resolve(data.data)
|
||||
@ -418,12 +451,11 @@ export function getShopDetail(params = {}) {
|
||||
uni.request({
|
||||
url: url,
|
||||
method: 'GET',
|
||||
dataType: 'text',
|
||||
header: {
|
||||
'Authorization': 'Bearer ' + token
|
||||
},
|
||||
success: (res) => {
|
||||
var data = typeof res.data === 'string' ? safeJsonParse(res.data) : res.data
|
||||
var data = safeJsonParse(res.data)
|
||||
console.log('【上书详情】响应:', JSON.stringify(data))
|
||||
if (res.statusCode === 200 && data) {
|
||||
if (data.code === 200 && data.data) {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user