我正在使用JavaScript调用/batch API方法,一次获取多条消息。根据文档,它返回一个带有multipart/mixed内容类型的HTTP响应。我正在尝试将其作为JSON循环,但不确定如何转换。非常感谢您的任何帮助。谢谢!
我为此编写了一个小型库。你可以使用它,或者从代码中获得一些灵感:
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;
}