簡體   English   中英

在導致 oom 的大型數據集上解決 JSON.parse

[英]work around for JSON.parse on large data set causing oom

在我進行 API 調用並取回壓縮數據的項目中工作。 然后我將該數據解壓縮成一個字符串。 該字符串為 JSON 格式,可以使用 Z0ECD11C1D7A287401F8Z 和 Z0ECD11C1D7A287401FZ4D.Z0ECD11C1D7A287401FZ4D. 但是有些數據相當大,JSON.parse 用完 memory。 我正在尋找一種解決方法來將此字符串解析為 object,而不會遇到 memory 問題。

我已經研究了流,但無法找到與之相關的解決方案。

代碼是這樣的:

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 ZA8CFDE6331BD59EB2AC96F8911C4B666 然后將其添加到數組。

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 解析的速度,即使對於它沒有遇到 memory 問題的實例,但這可能只是與我正在使用的對象有關,而不是一直發生的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM