-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathjson-stream.js
More file actions
37 lines (30 loc) · 752 Bytes
/
json-stream.js
File metadata and controls
37 lines (30 loc) · 752 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function JSONStream (cb) {
this.cb = cb;
this.obj = 0;
this.str = false;
this.esc = false;
}
JSONStream.prototype.decode = function (str) {
for (let i = 0; i < str.length; i++) this.decodeChar(str[i]);
};
JSONStream.prototype.decodeChar = function (c) {
// Start catching new object
if (!this.str && c === '{' && this.obj++ === 0) {
this.data = '';
}
// Add character
this.data += c;
// Hide brackets in strings
if (c === '"' && !this.esc) this.str = !this.str;
// Track escape chars
if (!this.esc && c === '\\') {
this.esc = true;
} else if (this.esc) {
this.esc = false;
}
// Stop at closing bracket
if (!this.str && c === '}' && --this.obj === 0) {
this.cb(JSON.parse(this.data));
}
};
module.exports = JSONStream;