@
bertonzh 试着写出来了:
*( V 站排版原因,行首有全角空格)*
```javascript
function parseJson(json) {
function restore(obj) {
if (typeof obj === 'number')
return nums[obj];
else if (Array.isArray(obj))
obj.forEach((v, i) => obj[i] = restore(v));
else if (typeof obj === 'object' && obj !== null)
Object.keys(obj).forEach(k => obj[k] = restore(obj[k]));
return obj;
}
let nums = [];
return restore(JSON.parse(json.replace(/"(?:\\?.)*?"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, m =>
m[0] === '"' ? m : nums.push(/[.eE]/.test(m) || Number.isSafeInteger(+m) ? +m : BigInt(m)) - 1
)));
}
```
拿了个本地 64.8 MB 的 `~/.conda/pkgs/cache/e5e4a514.json` 测了下速度: *( i5-8250U ,`nodejs` v16 )*
- #5 楼的方法:3.3 s
- 此楼方法:2.2 s = 正则替换 1.5 s + json 解析 0.4 s + 递归替换 0.3 s
- `json-bigint` *(`{useNativeBigInt: true}`)*:1.7 s