3

I have a stream of data like this:

{"foo": 1} {"bar": 2}

Note: no commas between these maps.

I want to read this stream in node.js so that I can capture the two maps, as shown above. I have been trying to do this with JSONStream, which is good at identifying the discrete JSON entities within the stream, but which mutates the data somewhat. So the code I am running is:

var jsonStream = require('JSONStream');
var es = require('event-stream');

var parser = jsonStream.parse('$*');
process.stdin.pipe(parser)
.pipe(es.mapSync(function (data) {
    console.log(data);
}));

And this outputs:

{ value: 1, key: 'foo' }
{ value: 2, key: 'bar' }

I want it to output the unchanged JSON maps:

{"foo": 1}
{"bar": 2}

Anyone know how I can achieve this, with JSONStream or something else?

clumsyjedi
  • 477
  • 6
  • 15

1 Answers1

3

Looks like JSONStream is more than is needed to solve this problem, under the hood it uses jsonparse, so a solution to my problem is:

var Parser = require('jsonparse');

var parser = new Parser();
process.stdin.on("readable", function () {
    var chunk = process.stdin.read();
    if (chunk) {
        parser.write(chunk);
    }
});

parser.onValue = function (v) {
    if (this.stack.length === 0) {
        console.log(v);
    }
};
clumsyjedi
  • 477
  • 6
  • 15