Cocoa Nub
Cocoa Nub

Reputation: 499

Parsing Gmail Batch response in Javascript

I'm using javascript to call the /batch API method for getting a number of messages at once. According to the docs it returns an HTTP response with a multipart/mixed content type. I'm trying to loop through this as JSON, but am not sure how to convert it. Any help would be greatly appreciated. Thanks!

Upvotes: 4

Views: 1670

Answers (2)

Nate Cheng
Nate Cheng

Reputation: 464

This is my quick parsing, not perfect, but did the trick while ago.

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;
}

Upvotes: 1

Tholle
Tholle

Reputation: 112807

I have written a tiny library for this. You could use that or maybe get some inspiration from the code:

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;
}

Upvotes: 7

Related Questions