Nodejs:JSONStream解析方法正则表达式

时间:2014-01-14 11:27:57

标签: regex json node.js jsonstream

我有这样的有效载荷

{
    "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"
            }
        }
    }]
}

我只需要从json有效负载中提取RESOURCE标记的内容。你能帮我制定正则表达式吗?以下是我尝试过的,它不会调用parser.data方法。

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

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

1 个答案:

答案 0 :(得分:4)

您不需要正则表达式:

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

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

输出:

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