Js解决long(大整数)精度丢失

js解决long(大整数)精度丢失

<script type="text/javascript">
    function getRealJsonData(baseStr) {
        if (!baseStr || typeof baseStr != 'string') return null;
        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 + '":[0-9]{15,}/'));
            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) {
            if (obj.hasOwnProperty(key)) {
                var value = obj[key];
                if (typeof value == 'number' && value > 9007199254740992) {
                    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":12313352677239567885445,' +
    '"id2":12313472667239127885446}]},"q":"52"}}';
    var data = getRealJsonData(testString);//直接放要解析的json字符串
    console.log(data);
</script>

你可能感兴趣的:(Web)