//主入口
function getRealJsonData(baseStr) {
if (!baseStr || typeof baseStr != 'string') return;
var jsonData = null;
try {
jsonData = JSON.parse(baseStr);
} catch (err) {
return null;
}
var needReplaceStrs = [];
loopFindArrOrObj(jsonData, needReplaceStrs);
needReplaceStrs.forEach(function (replaceInfo) {
var matchArr = baseStr.match(eval('/"' + replaceInfo.key + '":(\\-|\\+)?\\d+(\\.\\d+)?/'));
console.log(matchArr)
if (matchArr) {
var str = matchArr[0];
var replaceStr = str.replace('"' + replaceInfo.key + '":', '"' + replaceInfo.key + '":"');
replaceStr += '"';
baseStr = baseStr.replace(str, replaceStr);
}
});
var returnJson = null;
try {
returnJson = JSON.parse(baseStr);
} catch (err) {
return null;
}
return returnJson;
}
//遍历对象类型的
function getNeedRpStrByObj(obj, needReplaceStrs) {
for (var key in obj) {
var value = obj[key];
console.log(value)
if (typeof value == 'number' && value >= 0.0) {
needReplaceStrs.push({ key: key });
}
loopFindArrOrObj(value, needReplaceStrs);
}
}
//遍历数组类型的
function getNeedRpStrByArr(arr, needReplaceStrs) {
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
loopFindArrOrObj(value, needReplaceStrs);
}
}
//递归遍历
function loopFindArrOrObj(value, needRpStrArr) {
var valueTypeof = Object.prototype.toString.call(value);
if (valueTypeof == '[object Object]') {
needRpStrArr.concat(getNeedRpStrByObj(value, needRpStrArr));
}
if (valueTypeof == '[object Array]') {
needRpStrArr.concat(getNeedRpStrByArr(value, needRpStrArr));
}
}
//使用:
var testString = '{"a":{"b":{"n":[{"a":"138476506","ad":"us","se":"测",' +
'"e":"0","r":"0.0","s":"1","t":"2","c":"0","id1":352677239567885445,' +
'"id2":472667239127885446}]},"q":"52","f":1.32123123130000}}';
var data = getRealJsonData(testString);//直接放要解析的json字符串
console.log(data);
转自 JS大坑之JSON解析时,数字超过一定位数精度丢失,导致数据有误的解决办法 -
修改了验证规则,现在是大于或者等于0的 只要是数字 都会验证