Nodejs: JSONStream parse method regex

1.8k views Asked by At

I have a payload like this

{
    "rows": [{
        "id": "1234",
        "data": {
            "updatedby": "uid1",
            "resource": {
                "resourceid": "abcd"
            }
        }
    }, {
        "id": "1235",
        "data": {
            "updatedby": "uid2",
            "resource": {
                "resourceid": "pqrs"
            }
        }
    }, {
        "id": "1236",
        "data": {
            "updatedby": "uid3",
            "resource": {
                "resourceid": "bert"
            }
        }
    }]
}

I need to extract the content of the RESOURCE tag only from the json payload. Can you please help me formulate the regex? The below is what I tried and it doesn't invoke the parser.data method.

var parser = JSONStream.parse(['rows', true, /^resource/]);

parser.on('data', function(data) {
    console.log('received the payload -do something');
});
1

There are 1 answers

6
Paul Mougel On BEST ANSWER

You don't need a Regex:

var JSONStream = require('JSONStream');
var fs = require('fs');

fs.createReadStream('data.json')
.pipe(JSONStream.parse('rows.*.data.resource'))
.on('data', console.log.bind(console))

which outputs:

{ resourceid: 'abcd' }
{ resourceid: 'pqrs' }
{ resourceid: 'bert' }