javascript - 在导致 oom 的大型数据集上解决 JSON.parse
问题描述
在我进行 API 调用并取回压缩数据的项目中工作。然后我将该数据解压缩成一个字符串。此字符串为 JSON 格式,可通过 JSON.parse(data) 制作成所需的 JSON 对象。但是有些数据非常大,并且 JSON.parse 内存不足。我正在寻找一种解决方法,以一种不会遇到内存问题的方式将此字符串解析为对象。
我已经研究过流,但无法找到与之相关的解决方案。
代码是这样的:
let data = apiCall() //returns base64 encoded data
let stringData = decryptData(data) //returns a string of JSON data
return makeJSONObject(stringData) //return JSONObject (what is needed)
解决方案
在我的情况下有效的解决方案。
因为问题是要解析大量 JSON 对象,所以我能够根据分隔符拆分字符串,解析较小的 JSON 对象,然后将其添加到数组中。
let cursor = 0;
let arr = [];
while (cursor !== -1) {
let substring = "";
//Get the start and end indexes of the object
let start = returnValue.indexOf("{", cursor);
let end = returnValue.indexOf("}", start) + 1;
cursor = end;
//If one of the indexes is -1 it will not be a complete object so break.
if (cursor === -1 || start === -1 || end === -1) break;
//get the substring of the object
substring = returnValue.substring(start, end);
//If there are more than 2 opening braces before the first closing brace we have a nested object
if (substring.split("{").length > 2) {
//Increase the end point of our substring till we have the same amount of opening braces as closing braces
while (substring.split("{").length > substring.split("}").length) {
end = returnValue.indexOf("}", end) + 1;
cursor = end;
substring = returnValue.substring(start, end);
}
}
//add the parsed smaller object to our array of objects
arr.push(JSON.parse(substring));
}
这个解决方案似乎实际上提高了 JSON 解析的速度,即使对于它没有遇到内存问题的实例也是如此,但这可能只是与我正在使用的对象有关,而不是一直发生的事情。
推荐阅读
- node.js - 配置 Node.js 应用程序以使用 TCP 上的 Websockets 以及 AWS S3
- javascript - 复杂的 Promise 和 for 循环
- javascript - 事件下拉菜单不适用于 safari 中的图标
- sql-server - 将 sql 输出存储在 vba 变量中
- java - 如何解析 jsoup Elements 属性?
- sql - SQL 不确定如何使用选择计数作为子查询?
- python-3.x - brew install 没有链接python3
- swift - 如何在firebase中提取ID的某些部分等于某个字符串的所有孩子
- apache-spark - spark 1.5.2 左外连接不起作用
- macos - 生成 mozilla-central 的调用图 - 运行 Valgrind 时出错:启动失败。找不到二进制文件