JSON parser that extracts JSON objects out of a byte stream without the use of delimeters.
Ideal for extracting JSON objects out of an incoming TCP socket byte stream.
Install with npm:
$ npm install chunk2json
const ChunkParser = require("chunk2json");
const parser = new ChunkParser();
parser.on("json", (jsonBuff) => {
const result = JSON.parse(jsonBuff);
console.log(result); // Prints the expected array
});
parser.consume(new Buffer('[{"name": "Frank Castle"'));
parser.consume(new Buffer(',"kills": true,'));
parser.consume(new Buffer('"line": "One batch, two batch, penny and dime"}'));
parser.consume(new Buffer(',{"name": "Bruce Wayne"'));
parser.consume(new Buffer(',"kills": false,'));
parser.consume(new Buffer('"line": "I am the goddamn Batman"}]'));
The parser consumes buffers which can contain partial and/or complete JSON chunks. When a complete JSON object is identified the on("json")
event callback is invoked with the corresponding JSON object(in buffer form).
Run the tests
$ npm test
Copyright (c) 2016 Ioannis Tzanellis
Released under the MIT license