首页 > 解决方案 > 在导致 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)

标签: javascriptreact-native

解决方案


在我的情况下有效的解决方案。

因为问题是要解析大量 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 解析的速度,即使对于它没有遇到内存问题的实例也是如此,但这可能只是与我正在使用的对象有关,而不是一直发生的事情。


推荐阅读