我一直在尝试使用JSONStream读取文件,但我在这方面没有太多经验,而且很难找到有关它的信息(教程、文档)。
我在这里的某个地方发现了这段代码:
var fs = require('fs'),
JSONStream = require('JSONStream');
var stream = fs.createReadStream('tst.json', {encoding: 'utf8'}),
parser = JSONStream.parse();
stream.pipe(parser);
console.log(parser);
parser.on('root', function (obj) {
console.log(obj); // whatever you will do with each JSON object
});我尝试将其用于json测试文件,如下所示:
{
"colors": [{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255, 255, 255, 1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0, 0, 0, 1],
"hex": "#FFF"
}
},
{
"color": "red",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255, 0, 0, 1],
"hex": "#FF0"
}
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"code": {
"rgba": [0, 0, 255, 1],
"hex": "#00F"
}
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255, 255, 0, 1],
"hex": "#FF0"
}
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"code": {
"rgba": [0, 255, 0, 1],
"hex": "#0F0"
}
}
]
}我以为它会返回所有的对象,但是什么都没有发生,它甚至没有出现在"parser.on('root',function (Obj))“中。我能做些什么来让它工作呢?
发布于 2018-03-15 19:34:15
已从JSONStream中删除root事件。请改用data事件。https://github.com/dominictarr/JSONStream/commit/97d973ac59d0e58748cec98ea87aae36e057d368
还应该将JSON path指定为JSONStream.parse()的参数。对于JSON,它可以是JSONStream.parse('colors.*')。
所以把所有的东西放在一起,应该是
var fs = require('fs'),
JSONStream = require('JSONStream');
var stream = fs.createReadStream('tst.json', {encoding: 'utf8'}),
parser = JSONStream.parse('colors.*');
stream.pipe(parser);
parser.on('data', function (obj) {
console.log(obj); // whatever you will do with each JSON object
});https://stackoverflow.com/questions/49288779
复制相似问题