在 Javascript 中解析 Gmail 批处理响应

Parsing Gmail Batch response in Javascript

我正在使用 javascript 调用 /batch API 方法来一次获取大量消息。根据文档,它 returns 具有 multipart/mixed 内容类型的 HTTP 响应。我试图以 JSON 的形式遍历它,但我不确定如何转换它。任何帮助将不胜感激。谢谢!

我为此写了一篇tiny library。您可以使用它或者从代码中获得一些灵感:

function parseBatchResponse(response) {
  // Not the same delimiter in the response as we specify ourselves in the request,
  // so we have to extract it.
  var delimiter = response.substr(0, response.indexOf('\r\n'));
  var parts = response.split(delimiter);
  // The first part will always be an empty string. Just remove it.
  parts.shift();
  // The last part will be the "--". Just remove it.
  parts.pop();

  var result = [];
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    var p = part.substring(part.indexOf("{"), part.lastIndexOf("}") + 1);
    result.push(JSON.parse(p));
  }
  return result;
}

这是我的快速解析,并不完美,但前段时间成功了。

parseBatchResponse(response) {
    const result = [];

    const lines = response.split('\r\n');

    for (const line of lines) {
       if (line[0] === '{') {
           console.log(JSON.parse(line));
       }
    }
    return result;
}