Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80665 views
1
"use strict";
2
3
function JSONStreamParser() {
4
this._currentlyWithinQuotedString = false;
5
this._depth = 0;
6
this._buffer = '';
7
}
8
9
JSONStreamParser.prototype.parse=function(streamText) {
10
var cursor = this._buffer.length;
11
this._buffer += streamText;
12
var currChar;
13
var responses = [];
14
while (cursor < this._buffer.length) {
15
currChar = this._buffer.charAt(cursor);
16
if (this._currentlyWithinQuotedString && currChar === '\\') {
17
// If the current character is escaped, move forward
18
cursor++;
19
} else if (currChar === '"') {
20
// Are we inside a quoted string?
21
this._currentlyWithinQuotedString = !this._currentlyWithinQuotedString;
22
} else if (!this._currentlyWithinQuotedString) {
23
if (currChar === '{') {
24
this._depth++;
25
} else if (currChar === '}') {
26
this._depth--;
27
if (this._depth === 0) {
28
responses.push(JSON.parse(this._buffer.substring(0, cursor + 1)));
29
this._buffer = this._buffer.substring(cursor + 1);
30
cursor = 0;
31
continue;
32
}
33
}
34
}
35
cursor++;
36
}
37
return responses;
38
};
39
40
JSONStreamParser.prototype.getBuffer=function() {
41
return this._buffer;
42
}
43
44
module.exports = JSONStreamParser;
45
46