我一直在尝试使用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))”中。
我该怎么做才能使这项工作?

最佳答案

root事件已从JSONStream中删除​​。请改用data事件。 https://github.com/dominictarr/JSONStream/commit/97d973ac59d0e58748cec98ea87aae36e057d368

还应将JSON路径指定为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
});

07-24 20:10