-1

我有一个 JSON 字符串,它是一个数组。

arrayString = "[
  { fName: 'John', lName: 'Doe'},
  { fName: 'Jane', lName: 'Doe'},
  { fName: 'Josh', lName: 'Doe'},
  { fName: 'Jack', lName: 'Doe'},
  { fName: 'Jill', lName: 'Doe'},
  { fName: 'Josh', lName: 'Doe'},
  { fName: 'Jean', lName: 'Doe'},
  { fName: 'Jake', lName: 'Doe'},
  { fName: 'Judy', lName: 'Doe'},
  { fName: 'Jery', lName: 'Doe'},
]";

假设这是一个包含数千个元素的数组。如果我使用 .json() 一次解析它,它将占用大量内存。我想做的是只解析我需要的前 n 行,比如从字符串中检索数据的客户端分页。我无法控制如何从服务器传递大量数据。

4

1 回答 1

0

这个问题应该通过正确的 API 设计在服务器端处理,但您也可以查看range requests。使用它们,您可以请求部分数据,拒绝最后一个很可能格式错误的数据并重复。它确保客户端不会一次下载并保存过多的数据。

但是如果你想坚持解析整个数据集的部分,这已经在客户端机器上,那么这对于来自 ES6(ES2015)的生成器来说是一个很好的用例:

/**
 * Generator yielding a given number of records at a time.
 * @param {string} data          Data from which to extract.
 * @param {number} n             Number of objects per yield.
 * @yield {string} Array with the specified number of objects. Represented as
 *                 JSON-valid string.
 */
function* getNRecords(data, n) {
  let index = 0;
  while (index < data.length) {
    let result = data.substring(index).split('}', n).join('}');

    result = result.endsWith('}]') ? result : result + '}]';
    result = index > 0 ? '[' + result.trim() : result; // !result.startsWith('[') ?
    
    index += result.length;
    yield result;
  }
}

/* === EXAMPLE === */

const exampleData = '[{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}, {g: 7, h: 8}]';
const batchSize = 3;

for (let nRecords of getNRecords(exampleData, batchSize)) {
  console.log(nRecords); // TODO parse here
}

此处最多占用 N 个对象:data.substring(index).split('}', n).join('}');.

于 2018-11-05T21:08:10.173 回答